• WPF自定义控件(二)の重写原生控件样式模板


           

    WPF控件官方样式表 https://docs.microsoft.com/zh-cn/dotnet/framework/wpf/controls/datepicker-styles-and-templates

    话外篇: 要写一个圆形控件,用Clip,重写模板,去除样式引用圆形图片可以有这三种方式。

      开发过程中,我们有时候用WPF原生的控件就能实现自己的需求,但是样式、风格并不能满足我们的需求,那么我们该怎么办呢?----自定义样式与模板。

    一、样式

    在WPF中我们可以使用Style来设置控件的某些属性值,并使该设置影响到指定范围内的所有该类控件或影响指定的某一控件,比如说我们想将窗口中的所有按钮都保持某一种风格,那么我们可以设置一个Style,而不必分别设置每个按钮的风格。Style是作为一种资源被保存下来的. 看下面的例子:

                <Style x:Key="style1" TargetType="{x:Type Button}">
                    <Setter Property="Background" Value="Skyblue" />
                    <Setter Property="FontSize" Value="18" />
                    <Setter Property="FontFamily" Value="Verdena" />
                    <Setter Property="FontWeight" Value="Bold" />
                </Style>

    如果我们希望是动态样式,可以添加trigger:

          <Style.Triggers>
            <Trigger Property="IsPressed" Value="True">
            <Setter Property="Foreground" Value="Red"/>
            </Trigger>
          </Style.Triggers>

    二、模板

    ControlTemplate 指定控件的可视结构和可视行为。可以通过为控件指定新 ControlTemplate 自定义该控件的外观。创建 ControlTemplate 后,可以在不更改现有控件的功能的情况下更改其外观。例如,您可以将应用程序中的按钮设置为圆形,而不是默认的方形,但该按钮仍将引发 Click 事件。 注意: 在重定义模板前,你应该充分了解该空间的模板类型

    定义模板的方法有三种:

       1.内联定义: 

    <Button Content="Button1">
      <Button.Template>
        <ControlTemplate TargetType="Button">
          <!--Define the ControlTemplate here.-->
        </ControlTemplate>
      </Button.Template>
    </Button> 

    2.定义为资源:
    <StackPanel>
      <StackPanel.Resources>
        <ControlTemplate TargetType="Button" x:Key="newTemplate">
          <!--Define the ControlTemplate here.-->
        </ControlTemplate>
      </StackPanel.Resources>
      <Button Template="{StaticResource newTemplate}" Content="Button1"/>
    </StackPanel>

    3.通过Style定义:
    <StackPanel>
      <StackPanel.Resources>
        <Style TargetType="Button" x:Key="newTemplate"> 
          <Setter Property="Template">
            <Setter.Value>
              <ControlTemplate TargetType="Button">
                <!--Define the ControlTemplate here.-->
              </ControlTemplate>
            </Setter.Value>
          </Setter>
        </Style>
      </StackPanel.Resources>
      <Button Style="{StaticResource newTemplate}" Content="Button1"/>
    </StackPanel>

    由于模板的代码比较多,点此下载

    自定义控件系列博文链接:

    WPF自定义控件(一)の控件分类 
    WPF自定义控件(二)の重写原生控件样式模板
    WPF自定义控件(三)の扩展控件 
    WPF自定义控件(四)の自定义控件
    WPF自定义控件(五)の用户控件

  • 相关阅读:
    部分网络加载预训练模型代码实现
    数据不平衡处理方法
    面试题目汇总
    多线程和多进程
    数据结构知识点总结
    GBDT和XGBoost的区别
    GBDT和随机森林的区别
    机器学习-特征处理
    一篇写得很好的关于lct的博客
    Count and Say 2014/10/23
  • 原文地址:https://www.cnblogs.com/xietianjiao/p/7569064.html
Copyright © 2020-2023  润新知