zoukankan      html  css  js  c++  java
  • 【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

  • 相关阅读:
    Nginx + uWSGI 配置django
    django视图缓存的实现
    scrapy 资料
    scrapy 安装
    程序题做题一般步骤
    检查代码的一般步骤
    Mathematical-Analysis-I-4
    Mathematical-Analysis-I-3
    Mathematical-Analysis-I-1
    Mathematical-Analysis-I-2
  • 原文地址:https://www.cnblogs.com/guxin/p/wpf-dynamically-change-ui-control-style.html
Copyright © 2011-2022 走看看