3

我目前正在创建一个自定义控件(基于 WPF DataGrid)。我想做的是在数据网格上设置默认样式。目前我正在设置有效的 Style 属性。但是当我创建一种样式来更改 fx 时,我的问题就出现了。主应用程序 app.xaml 中的背景颜色。然后我所有的“默认”样式都丢失了,DataGrid 看起来都是标准的,只有背景属性集。

我尝试在网格上的每个属性上使用 OverrideMetadata,我想对其应用默认值但没有运气。我还尝试在构造函数中设置每个属性,但由于属性优先,主应用程序中的样式永远不会被应用。

有任何想法吗?

提前致谢

4

2 回答 2

13

你在static构造函数中设置了吗?

DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomType), new FrameworkPropertyMetadata(typeof(MyCustomType)));

另外,资源样式的键是否等于自定义控件的类型?

即使将 TargetType 设置为您的控件,它也不能有其他键集。

程序集还应标有以下属性:

[assembly: ThemeInfo(
    //where theme specific resource dictionaries are located
    //(used if a resource is not found in the page, 
    // or application resource dictionaries)
    ResourceDictionaryLocation.None, 

    //where the generic resource dictionary is located
    //(used if a resource is not found in the page, 
    // app, or any theme specific resource dictionaries)
    ResourceDictionaryLocation.SourceAssembly 
)]
于 2009-08-06T14:07:56.707 回答
5

如果您创建一个没有字典键的样式,它将为您在导入样式字典的范围内指定类型的所有对象设置样式(如果您在 Window.Resources 中指定它,它将具有该窗口的范围...如果你在 App.xaml 中指定它......你会得到图片)。

  <Style TargetType="{x:Type Button}">
    <Setter Property="FontFamily" Value="Times New Roman" />
    <Setter Property="FontSize" Value="30" />
    <Setter Property="FontWeight" Value="Bold" />
    <Setter Property="Background" Value="#FFCA5132" />
  </Style>

这将使它们具有相同的风格。

这是一个非常强大的功能。它允许您设置任何对象的样式,而不仅仅是 UI 元素。例如,您可以设置一个数据实体的样式,例如“Person”对象,并且当这些元素以可视方式使用时,例如将 Person 类型的列表数据绑定到 ListView,所有这些元素都将按照您指定的方式设置样式,即使它们是不是原生的 UI 元素。这就是 WPF 如何对其控件“无视”的方式。

于 2009-08-06T12:18:35.883 回答