欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF何如在后台通过代码创建控件,如何使用资源样式

程序员文章站 2022-07-04 16:22:27
...

关于App.XML查找资源字典“*****.xaml”出错

一、后台写控件

后台代码简单来创建一个Button,并引用资源样式

       public MainWindow()
        {
            InitializeComponent();
            CreateControl0();

        }
         private void CreateControl0()
         {
            Button btn = new Button();
            btn.Width = 60;
            btn.Height = 40;
            Style style= (Style)this.FindResource("BtnInfoStyle");
            btn.Style = style;
            btn.Click += Btn_Click;          
            grid1.Children.Add(btn);

         }

        private void Btn_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("111");
        }

二、传教资源样式
如何创建上述使用的BtnInfoStyle.xml
1.项目右键-添加-新建项-资源词典(WPF)

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:WpfApp1">

    <!-- 应该在此定义资源字典条目。-->
    <Style x:Key="BtnInfoStyle" TargetType="Button">
        <Setter Property="Width" Value="70"/>
        <Setter Property="Height" Value="25"/>
        <Setter Property="Foreground" Value="White"/>
        <Setter Property="BorderThickness" Value="0"/>
        <Setter Property="Background" Value="#43a9c7"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="True">
                        <TextBlock Text="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="border" Property="Background" Value="#2f96b4"/>
                        </Trigger>
                        <Trigger Property="IsPressed" Value="True">
                            <Setter TargetName="border" Property="Background" Value="#2a89a4"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

2.app.XML中使用资源

 <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <!--App.xaml资源样式-->
                <ResourceDictionary  Source="BtnInfoStyle.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
相关标签: WPF