如何将样式应用于自定义控件

How to apply style to a custom control

我有一个继承自 ListBox 的自定义控件。

我有一个针对我的自定义控件的样式。

出于某种原因,此样式不适用于我的自定义控件。

你能告诉我我在这里遗漏了什么吗?

样式代码:

<Style x:Key="ListBoxStyle" TargetType="local:CustomListBox">
    <Setter Property="Background" Value="Red"/>
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"/>
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
</Style>

自定义控件代码:

public class CustomListBox : ListBox
{
    public CustomListBox()
    {
        this.DefaultStyleKey = typeof(CustomListBox).Name;
    }

}

自定义控件的使用:

<local:CustomListBox>
        <ListBoxItem Content="AAA"></ListBoxItem>
        <ListBoxItem Content="BBB"></ListBoxItem>
        <ListBoxItem Content="CCC"></ListBoxItem>
    </local:CustomListBox>

有什么帮助吗?

谢谢!

在 Windows Phone 8.1 中,当您创建模板化控件(自定义控件)时,会自动创建一个名为 Generic.xaml 的文件 [= =16=]Themes 文件夹。 您的样式应该像这样添加到 Generic.xaml 中。

<Style TargetType="local:CustomListBox">
    <Setter Property="Background" Value="Red"/>
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"/>
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter> 
</Style>

将以下行更改为

this.DefaultStyleKey = typeof(CustomListBox);