为自定义控件创建默认样式 [英] Creating default style for custom control

查看:62
本文介绍了为自定义控件创建默认样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在创建自定义控件(基于WPF DataGrid)。我想做的是在datagrid上设置默认样式。目前,我正在设置可以使用的Style属性。但是当我创建样式来更改fx时,我的问题浮出水面。主应用程序app.xaml中的背景色。然后,我所有的默认样式都将丢失,并且DataGrid仅在设置了背景属性的情况下看起来才是标准的。

Im currently creating a custom control (based on the WPF DataGrid). What i would like to do is to set default styling on the datagrid. Currently im setting the Style property which works. But my problem arrises when i create a style to change fx. the background color in the main applications app.xaml. Then all my "default" styling is lost and the DataGrid looks all standard only with the background property set.

我尝试在网格上的每个属性上使用OverrideMetadata我想将默认值应用于但没有运气。我也尝试过在构造函数中设置每个属性,但是由于属性优先,因此从主应用程序中获得的样式永远不会应用。

I have tried using OverrideMetadata on each of the properties on the grid that i want to apply a default value to but with no luck. I also tried setting each property in the constructor but because of property precedence the styles from the main application then never is applied.

有什么想法吗?

预先感谢

推荐答案

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

If you create a style without a dictionary key, it will style all objects of the type you specify within the scope that you import your style dictionary (if you specify it in a Window.Resources, it will have scope for that Window... if you specify it in App.xaml... you get the picture).

  <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>

这将赋予它们相同的样式。

This will give them all the same style.

这是一个非常强大的功能。它允许您设置任何对象的样式,而不仅仅是UI元素。例如,您可以设置一个数据实体的样式,例如 Person对象,并且当可视地使用这些元素时(例如将Person类型的列表数据绑定到ListView时),即使它们是不是本机的UI元素。这就是WPF对其控件看不清的方式。

This is a very powerful feature. It allows you to style any object, not just UI elements. You can style, say, one of your data entities like a "Person" object and when those elements are used visually, like databinding a list of type Person to a ListView, all of them will be styled how you specified, even though they are not natively UI elements. This is how WPF can be "lookless" about its controls.

这篇关于为自定义控件创建默认样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆