WPF 中,动态创建Button,并使Button得样式按照自定义的Resource样式显示

第一步:自定义一个Button的样式

1.新建一个xaml文件,在其中自定义好自己的Resources

这个Resource 的根节点是

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"></ResourceDictionary>

2.然后在根节点中写入自己要定义的样式,

注意,在对应特定控件的样式中,要写入  TargetType 对应于要设置样式的控件,如:

TargetType="{x:Type Button}",并且对样式写上x:key= 以便查找:

入下面一个例子:

<ResourceDictionary
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Classic"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Style x:Key="GlassYButton" TargetType="{x:Type Button}">
        <Setter Property="SnapsToDevicePixels" Value="True"/>
        <Setter Property="OverridesDefaultStyle" Value="True"/>
        <Setter Property="FontSize" Value="15" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid>
                        <!-- Background Layer -->
                        <Ellipse Fill="{TemplateBinding Background}"/>
                        <!-- Refraction Layer -->
                        <Ellipse x:Name="RefractionLayer">
                            <Ellipse.Fill>
                                <RadialGradientBrush GradientOrigin="0.496,1.052">
                                    <RadialGradientBrush.RelativeTransform>
                                        <TransformGroup>
                                            <ScaleTransform CenterX="0.5" CenterY="0.5" ScaleX="1.5" ScaleY="1.5"/>
                                            <TranslateTransform X="0.02" Y="0.3"/>
                                        </TransformGroup>
                                    </RadialGradientBrush.RelativeTransform>
                                    <GradientStop Offset="1" Color="#00000000"/>
                                    <GradientStop Offset="0.4" Color="#FFFFFFFF"/>
                                </RadialGradientBrush>
                            </Ellipse.Fill>
                        </Ellipse>
                        <!-- Reflection Layer -->
                        <Path x:Name="ReflectionLayer" VerticalAlignment="Top" Stretch="Fill">
                            <Path.RenderTransform>
                                <ScaleTransform ScaleY="0.5" />
                            </Path.RenderTransform>
                            <Path.Data>
                                <PathGeometry>
                                    <PathFigure IsClosed="True" StartPoint="98.999,45.499">
                                        <BezierSegment Point1="98.999,54.170" Point2="89.046,52.258" Point3="85.502,51.029"/>
                                        <BezierSegment
                                    IsSmoothJoin="True"
                                    Point1="75.860,47.685"
                                    Point2="69.111,45.196"
                                    Point3="50.167,45.196"/>
                                        <BezierSegment Point1="30.805,45.196" Point2="20.173,47.741" Point3="10.665,51.363"/>
                                        <BezierSegment
                                    IsSmoothJoin="True"
                                    Point1="7.469,52.580"
                                    Point2="1.000,53.252"
                                    Point3="1.000,44.999"/>
                                        <BezierSegment Point1="1.000,39.510" Point2="0.884,39.227" Point3="2.519,34.286"/>
                                        <BezierSegment
                                    IsSmoothJoin="True"
                                    Point1="9.106,14.370"
                                    Point2="27.875,0"
                                    Point3="50,0"/>
                                        <BezierSegment Point1="72.198,0" Point2="91.018,14.466" Point3="97.546,34.485"/>
                                        <BezierSegment
                                    IsSmoothJoin="True"
                                    Point1="99.139,39.369"
                                    Point2="98.999,40.084"
                                    Point3="98.999,45.499"/>
                                    </PathFigure>
                                </PathGeometry>
                            </Path.Data>
                            <Path.Fill>
                                <RadialGradientBrush GradientOrigin="0.498,0.526">
                                    <RadialGradientBrush.RelativeTransform>
                                        <TransformGroup>
                                            <ScaleTransform
                                       CenterX="0.5"
                                       CenterY="0.5"
                                       ScaleX="1"
                                       ScaleY="1.997"/>
                                            <TranslateTransform X="0" Y="0.5"/>
                                        </TransformGroup>
                                    </RadialGradientBrush.RelativeTransform>
                                    <GradientStop Offset="1" Color="#FFFFFFFF"/>
                                    <GradientStop Offset="0.85" Color="#92FFFFFF"/>
                                    <GradientStop Offset="0" Color="#00000000"/>
                                </RadialGradientBrush>
                            </Path.Fill>
                        </Path>
                        <!-- ContentPresenter -->
                        <ContentPresenter Margin="0,2,0,0" HorizontalAlignment="Center" VerticalAlignment="Center"/>

                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="RefractionLayer" Property="Fill">
                                <Setter.Value>
                                    <RadialGradientBrush GradientOrigin="0.496,1.052">
                                        <RadialGradientBrush.RelativeTransform>
                                            <TransformGroup>
                                                <ScaleTransform
                                          CenterX="0.5"
                                          CenterY="0.5"
                                          ScaleX="1.5"
                                          ScaleY="1.5"/>
                                                <TranslateTransform X="0.02" Y="0.3"/>
                                            </TransformGroup>
                                        </RadialGradientBrush.RelativeTransform>
                                        <GradientStop Offset="1" Color="#00000000"/>
                                        <GradientStop Offset="0.45" Color="#FFFFFFFF"/>
                                    </RadialGradientBrush>
                                </Setter.Value>
                            </Setter>
                            <Setter TargetName="ReflectionLayer" Property="Fill">
                                <Setter.Value>
                                    <RadialGradientBrush GradientOrigin="0.498,0.526">
                                        <RadialGradientBrush.RelativeTransform>
                                            <TransformGroup>
                                                <ScaleTransform
                                          CenterX="0.5"
                                          CenterY="0.5"
                                          ScaleX="1"
                                          ScaleY="1.997"/>
                                                <TranslateTransform X="0" Y="0.5"/>
                                            </TransformGroup>
                                        </RadialGradientBrush.RelativeTransform>
                                        <GradientStop Offset="1" Color="#FFFFFFFF"/>
                                        <GradientStop Offset="0.85" Color="#BBFFFFFF"/>
                                        <GradientStop Offset="0" Color="#00000000"/>
                                    </RadialGradientBrush>
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                        <Trigger Property="IsPressed" Value="True">
                            <Setter TargetName="RefractionLayer" Property="Fill">
                                <Setter.Value>
                                    <RadialGradientBrush GradientOrigin="0.496,1.052">
                                        <RadialGradientBrush.RelativeTransform>
                                            <TransformGroup>
                                                <ScaleTransform
                                          CenterX="0.5"
                                          CenterY="0.5"
                                          ScaleX="1.5"
                                          ScaleY="1.5"/>
                                                <TranslateTransform X="0.02" Y="0.3"/>
                                            </TransformGroup>
                                        </RadialGradientBrush.RelativeTransform>
                                        <GradientStop Offset="1" Color="#00000000"/>
                                        <GradientStop Offset="0.3" Color="#FFFFFFFF"/>
                                    </RadialGradientBrush>
                                </Setter.Value>
                            </Setter>
                            <Setter TargetName="ReflectionLayer" Property="Fill">
                                <Setter.Value>
                                    <RadialGradientBrush GradientOrigin="0.498,0.526">
                                        <RadialGradientBrush.RelativeTransform>
                                            <TransformGroup>
                                                <ScaleTransform
                                          CenterX="0.5"
                                          CenterY="0.5"
                                          ScaleX="1"
                                          ScaleY="1.997"/>
                                                <TranslateTransform X="0" Y="0.5"/>
                                            </TransformGroup>
                                        </RadialGradientBrush.RelativeTransform>
                                        <GradientStop Offset="1" Color="#CCFFFFFF"/>
                                        <GradientStop Offset="0.85" Color="#66FFFFFF"/>
                                        <GradientStop Offset="0" Color="#00000000"/>
                                    </RadialGradientBrush>
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>

2.

第二步:在项目的配置文件 App.xaml 中配置 自定义Resources

在 App.xml根节点下面建立一个 <Application.Resources>,其中定义ResourceDictionary节点

在其中配置自己定义的Resources,例如:

<Application x:Class="PaperOfficerPro.App"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary  Source="Resource/ButtonResource.xaml"></ResourceDictionary>
                <ResourceDictionary  Source="Resource/ExpanderStyleResource.xaml"></ResourceDictionary>
                <ResourceDictionary  Source="Resource/GlassButtonStyle.xaml"></ResourceDictionary>
                <ResourceDictionary  Source="Resource/DataGridResource.xaml"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

 

第三步:在页面的后台写程序动态生成Button,

这里的实例是,检索数据库,根据检索的数据动态生成一个按钮,按钮的个数是检索出来的数据的条数

例如:

private void initCourseButton()
       {
           PaperDBHelper.ConnectDB();
           String sql = "select keyID ,courseID,courseName from course order by keyID ";
           DataSet courseDS = PaperDBHelper.GetDataSet(CommandType.Text, sql, null);
           DataTable dt = courseDS.Tables[0];
           for (int i = 0; i < dt.Rows.Count; i++)  //for循环检索出来的数据,生成Button
           {
               Button button = new Button();
               button.Content = dt.Rows[i]["courseName"]; //Button按钮上的显示内容为数据库中的一个字段值
               button.Width = 80;
               button.Height = 50;
               button.Margin = new Thickness(0 + i * 80, 507, 560 - i * 120, 4);//动态生成Button的位置
               button.Name = "button" + (i + 1);//动态生成Button的Name
               button.SetResourceReference(StyleProperty, "GlassYButton");//将自定义的样式赋值给Button

//的相应属性,第一个参数是第一步中的Resource是定义的Button的Style,因此第一个参数为StyleProperty

//意思是赋值给style这个属性,第二个参数是样式中的x:key的值
               button.Click += new RoutedEventHandler(btnEvent_Click);//为动态生成的Button添加事件
               this.ButtonGrid.Children.Add(button);//注意,最后要将自定义的Button控件加入到页面中包含它

//的容器中
               this.ButtonGrid.RegisterName("button" + (i + 1), button);//注册button的名称
           }

       }

时间: 2024-10-14 00:48:42

WPF 中,动态创建Button,并使Button得样式按照自定义的Resource样式显示的相关文章

html中动态创建表格

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>dtTable.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equ

WPF 中动态改变控件模板

在某些项目中,可能需要动态的改变控件的模板,例如软件中可以选择不同的主题,在不同的主题下软件界面.控件的样式都会有所不同,这时即可通过改变控件模板的方式实现期望的功能. 基本方法是当用户点击切换主题按钮是加载新的资源字典,并使用新加载的资源字典替代当前的资源字典这时要用到ResourceManager. 假设现有两个不同的资源字典文件Dictionary1.xaml和Dictionary2.xaml存在于Themes文件夹内: 在MainPage中使用其中一个资源字典作为默认样式文件: <Win

WPF中动态更新TextBlock文字中的超链接,文本

1.------------------------------------------------------------------------- 修改超链接的文本文字: <TextBlock><Hyperlink> <TextBlock  x:Name="TextBlockNeedChange" Text="改变的文本" /> </Hyperlink></TextBlock> 修改TextBlockN

Python中动态创建类实例

Python中动态创建类实例 简介 在Java中我们可以通过反射来根据类名创建类实例,那么在Python我们怎么实现类似功能呢? 其实在Python有一个builtin函数import,我们可以使用这个函数来在运行时动态加载一些模块.如下: def createInstance(module_name, class_name, *args, **kwargs): module_meta = __import__(module_name, globals(), locals(), [class_n

OC中动态创建可变数组的问题.有一个数组,数组中有13个元素,先将该数组进行分组,每3个元素为一组,分为若干组,最后用一个数组统一管理这些分组.(要动态创建数组).两种方法

<span style="font-size:24px;">//////第一种方法 // NSMutableArray *arr = [NSMutableArray array]; // for (int i = 0; i < 13; i ++) { // [arr addObject:[NSString stringWithFormat:@"lanou%d",i + 1]]; // } // NSLog(@"%@",arr);

DOM中动态创建元素与jQuery中动态创建元素

DOM中动态创建元素与jQuery中动态创建元素 DOM中动态创建元素: 1. document.write("标签的代码")    缺点:页面中原有的元素会被覆盖掉 2. innerHTML 3. document.createElement("标签的名称") jQuery中动态创建元素: 1. $("标签的代码") 2. 对象.html("标签的代码") 原文地址:https://www.cnblogs.com/david

在代码中动态创建控件无法保存状态的问题

在网上找了点资料,算是明白了,这是我觉得有帮助的文章: 原文:http://blog.csdn.net/keleloveni/archive/2007/03/15/1530300.aspx 引文: 今天偶然看到有篇文章谈到了相关的问题,终于又解决了一个自己不是很明白的东西. 页面生命周期中的第一个阶段是实例化,在这个阶段中,自动生成的类会根据页面的 HTML 部分中定义的静态控件构建控件层次结构.构造控件层次结构时,声明性语法中指定的值会赋给添加的每个控件的属性.实例化之后是初始化阶段,在这个阶

jQuery中动态创建、添加元素的方法总结

<input type="button" value="创建元素" id="btn"> <div id="box"></div> <p id="main">这是文中一段话</p> //点击按钮,动态创建元素 //方法一:$()创建元素,后用append()方法添加.append() 还可以把其他地方元素添加进这个对象中. $('#btn').cli

BroadcastReceiver接收电量变化的广播-------在代码中动态创建接受者

本例为动态创建广播接收者即不是在AndroidManifest.xml文件中定义的广播接收着 代码: 1 package com.qf.broadcastreceiver01; 2 3 import android.app.Activity; 4 import android.app.AlertDialog; 5 import android.content.BroadcastReceiver; 6 import android.content.Context; 7 import android