代码之家  ›  专栏  ›  技术社区  ›  Drake

WPF中的主题用户控件

  •  8
  • Drake  · 技术社区  · 17 年前

    如何在WPF中创建具有基本默认样式但在需要时也可以轻松主题化的UserControl?

    你有没有一些好的指南、博客或例子来解释这个特定的话题?

    提前谢谢, 马可

    2 回复  |  直到 17 年前
        1
  •  7
  •   Enrico Campidoglio    13 年前

    在WPF中,主题只是一组XAML文件,每个文件包含一个 字典资源 这是最重要的 风格 样板 适用于应用程序中使用的控件的定义。主题文件可能如下所示:

    <ResourceDictionary
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:uc="clr-namespace:MyApp.UserControls">
    
      <!-- Standard look for MyUserControl -->
      <Style x:Key="Standard" TargetType="{x:Type uc:MyUserControl}">
        <Setter Property="Width" Value="22" />
        <Setter Property="Height" Value="10" />
      </Style>
    
    </ResourceDictionary>
    

    必须通过向程序集添加以下属性来明确启用WPF应用程序中对主题的支持:

    [assembly: ThemeInfo(
      ResourceDictionary.None,
      ResourceDictionaryLocation.SourceAssembly
     )]
    

    这将指示WPF查找 嵌入式资源 文件名为 主题\通用。xaml 以确定应用程序控件的默认外观。

    请注意,当 特定于主题的词典包含单独的文件 而应用程序的程序集、样式和模板资源必须使用 复合密钥 ,它告诉WPF哪个程序集包含应用样式/模板的控件。因此,前面的示例应修改为:

    <ResourceDictionary
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:uc="clr-namespace:MyApp.UserControls;assembly=MyApp">
    
      <!-- Standard look for MyUserControl in the MyApp assembly -->
      <Style x:Key="{ComponentResourceKey {x:Type uc:MyUserControl}, Standard}">
        <Setter Property="Width" Value="22" />
        <Setter Property="Height" Value="10" />
      </Style>
    
    </ResourceDictionary>
    
        2
  •  1
  •   Nir    17 年前

    看看这篇文章: http://msdn.microsoft.com/en-us/magazine/cc135986.aspx

    它讨论了如何编写一个可以用ControlTemplate更改的控件,比如内置控件。