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

时间:2015-03-11 08:10:10

标签: c# xaml wpf-controls

我有一个继承自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>

任何帮助?

谢谢!

1 个答案:

答案 0 :(得分:2)

在Windows Phone 8.1中创建模板化控件(自定义控件)时,会自动在主题文件夹下创建名为 Generic.xaml 的文件。 你的风格应该像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);
相关问题