简体   繁体   中英

WPF content control styling

I have a custom control which is basically a contentcontrol

 public class PromoAlarmBox : ContentControl
    {
        static PromoAlarmBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(PromoAlarmBox), new FrameworkPropertyMetadata(typeof(PromoAlarmBox)));
        }
    }

I add it to the containing user control

<controls:PromoAlarmBox Grid.Row="9" Grid.Column="1"  />

If I add the style to the containing usercontrols resources everything works fine

 <UserControl.Resources>
        <Style  TargetType="{x:Type controls:PromoAlarmBox}">
            <Setter Property="ContentControl.ContentTemplate">
                <Setter.Value>
                    <DataTemplate >
                        <Rectangle Fill="Blue" Stroke="Black" Height="20" Width="20"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>

But if I add it to generic.xaml in the custom controls project , nothing is show

<Style  TargetType="{x:Type local:PromoAlarmBox}">
        <Setter Property="ContentControl.ContentTemplate">
            <Setter.Value>
                <DataTemplate >
                    <Rectangle Fill="Blue" Stroke="Black" Height="20" Width="20"/>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>

I know the style is applied as I have other controls in same project whos styles are defined in generic.xaml, Anyone have any ideas?

A simple static should do the trick...

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

Although im not sure why there is a difference when you use a style as a local resource and when you use generic , this works for me

<Style TargetType="{x:Type local:PromoAlarmBox}">

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ContentControl">
                    <Rectangle VerticalAlignment="Stretch" Fill="Yellow" Stroke="Black" Height="20" Width="20"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

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