简体   繁体   中英

WPF style not applied to all controls

Problem: Not all of my custom checkboxes are displayed in the same way and it is unclear to me, why.

I have a custom WPF CheckBox of which I generate instances at runtime.

The custom CheckBox :

public class CheckBoxQuickSelect : System.Windows.Controls.CheckBox
{
    public string Description { get; }

    public CheckBoxQuickSelect(string description)
        : base()
    {
        Description = description;

        Margin = new Win.Thickness(10, 0, 0, 0);
        VerticalAlignment = System.Windows.VerticalAlignment.Center;
        VerticalContentAlignment = System.Windows.VerticalAlignment.Center;
        Style = (System.Windows.Style)this.FindResource("MySettingsCheckBoxStyle");
    }
}

The part where I add the checkboxes at runtime:

foreach (string abbreviation in Helper.TreeSpecies.Keys)
{
    CheckBoxQuickSelect cb = new CheckBoxQuickSelect(abbreviation);
    cb.Name = Helper.MakeValidXmlName("checkBoxTreeSpecies_" + abbreviation);
    cb.Content = abbreviation.Replace("_", "__") + ": " + Helper.TreeSpecies[abbreviation][1];
    cb.IsChecked = Helper.TreeSpeciesQuickSelect.Contains(abbreviation);
    stackPanelTreeSpecies.Children.Add(cb);
}

The associated style in App.xaml :

<Style TargetType="CheckBox" x:Key="MySettingsCheckBoxStyle">
    <Setter Property="FontSize" Value="12" />
</Style>

There is also a general CheckBox style earlier in App.xaml (but it doesn't change anything if I comment that out):

<Style BasedOn="{StaticResource {x:Type CheckBox}}" TargetType="CheckBox">
    <Setter Property="FontSize" Value="{DynamicResource StandardFontSize}" />
</Style>

The problem now is: Only the checkboxes with an underscore in their abbreviations get displayed correctly:

显示自定义复选框

Why is that? What can I do to make all boxes look the same?

Instead of setting the Style property of your custom control at runtime in the constuctor, you should define a default Style for the control in a resource dictinonary called generic.xaml that is located inside a dictionary called themes at the root of the project/assembly where the custom control is defined:

<Style TargetType="{x:Type local:CheckBoxQuickSelect">
    <Setter Property="FontSize" Value="12" />
</Style>

You should then add a static constructor to the custom control class where the default value of the DefaultStyleKey property is set:

static CustomWindow()
{    
    DefaultStyleKeyProperty.OverrideMetadata(typeof(CheckBoxQuickSelect),
        new FrameworkPropertyMetadata(typeof(CheckBoxQuickSelect)));
}

This should ensure that the default appearance is always applied by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM