【问题标题】:Derived classes and theme inheritance in WPF?WPF中的派生类和主题继承?
【发布时间】:2010-11-01 14:38:38
【问题描述】:

我正在构建一个 WPF 应用程序,我从标准 WPF 控件类型派生了一堆控件——文本块、按钮等。我尝试将资源字典添加到 app.xaml 以设置主题,但我的自定义控制似乎不尊重它。 (例如,标准按钮采用 Aero 主题就好了,但从 Button 派生的 myButton 仍然不美观。)有没有办法可以将派生控件的主题设置为与基本控件相同?

编辑:我应该注意,这些自定义控件是在运行时实例化的,所以我不能直接通过 XAML 操作它们的属性。我可以通过在应用程序资源字典中使用 Setter 来更改背景颜色等特定属性,但还没有找到使用该技术设置主题的方法。

【问题讨论】:

    标签: wpf wpf-controls


    【解决方案1】:

    如果您在名为 Dictionary1.xaml 的资源字典中有此样式

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <Style x:Key="MyButtonStyle"
               TargetType="{x:Type Button}" 
               BasedOn="{StaticResource {x:Type Button}}">
            <Setter Property="Width" Value="75" />
            <Setter Property="Height" Value="23" />
        </Style>
    </ResourceDictionary>
    

    然后你可以在任何按钮上设置它,后面有这个代码

    Uri resourceLocater = new Uri("/YourAssemblyName;component/Dictionary1.xaml", System.UriKind.Relative);
    ResourceDictionary resourceDictionary = (ResourceDictionary)Application.LoadComponent(resourceLocater);
    Style myButtonStyle = resourceDictionary["MyButtonStyle"] as Style;
    
    Button button = new Button();
    button.Style = myButtonStyle;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多