簡體   English   中英

如何將樣式應用於自定義控件

[英]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的文件。 您的樣式應像這樣添加到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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM