【WPF】C#代码动态改变控件的样式

原文: 【WPF】C#代码动态改变控件的样式

需求:C#代码生成的一组按钮Button需要设置样式。

如果是在XAML中引入样式:

<!-- 引入资源 -->
<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!-- 引入颜色字符串 -->
            <ResourceDictionary Source="/Presentation/Resources/ColorResources.xaml" />
            <!-- 引入样式 -->
            <ResourceDictionary Source="/Presentation/Style/MyRadioButton.xaml" />
            <ResourceDictionary Source="/Presentation/Style/MyTextBlock.xaml" />
            <ResourceDictionary Source="/Presentation/Style/MyComboBox.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

但是现在由于按钮是用代码动态生成的,需要在生成时指定样式。样式文件已经单独抽取。

// 引入按钮的样式
var myResourceDictionary = new ResourceDictionary
{
    Source = new Uri("/ProjectName;component/Presentation/Style/MyButton.xaml", UriKind.RelativeOrAbsolute) // 指定样式文件的路径
};
var myButtonStyle = myResourceDictionary["myButton1"] as Style; // 通过key找到指定的样式

// 动态添加按钮
Button btn = new Button()
{
    Content = "这是按钮",
    Style = myButtonStyle, // 设置样式
};

重要的参考:

http://stackoverflow.com/questions/18813177/how-do-i-access-a-resourcestyle-through-code

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12741756.html