Creating default style for custom control

2019-07-04 06:41发布

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.

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.

Any ideas?

Thanks in advance

2条回答
一夜七次
2楼-- · 2019-07-04 07:01

Did you set this in the static constructor?

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

Also, is the Key of your resource Style equal to your custom control's Type?

It mustn't have some other Key set, even with TargetType set to your control.

The Assembly should also be marked with the following attribute:

[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 
)]
查看更多
We Are One
3楼-- · 2019-07-04 07:18

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.

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.

查看更多
登录 后发表回答