【问题标题】:How to set StyleSheets for ComboBoxItems in XAML如何在 XAML 中为 ComboBoxItems 设置样式表
【发布时间】:2015-04-14 13:05:54
【问题描述】:
<ComboBox 
        Foreground="Black"
        BorderBrush="Black"
        HorizontalAlignment="Left" Margin="108,280,0,0" VerticalAlignment="Top" Width="200" Style="{StaticResource ComboBoxStyl}"><ComboBoxItem Content="One" IsSelected="True" Style="{StaticResource ComboBoxItemStyle1}"/>
        <ComboBoxItem Content="Two" Style="{StaticResource ComboBoxItemStyle1}"/>
        <ComboBoxItem Content="Three" Style="{StaticResource ComboBoxItemStyle1}"/>
        <ComboBoxItem Content="Four" Style="{StaticResource ComboBoxItemStyle1}"/>
        <ComboBoxItem Content="Five" Style="{StaticResource ComboBoxItemStyle1}"/>
    </ComboBox>

这里我提到了每个 ComboBoxItem 的样式表。我只想引用一次样式表(相对于 ComboBoxItem)。因此,当向其中添加动态数据项时,样式将自动应用。

【问题讨论】:

  • 要将单一样式应用于所有项目,您可以使用ItemContainerStyle 像这样&lt;ComboBox ItemContainerStyle="{StaticResource ComboBoxItemStyle1}"&gt;

标签: xaml windows-phone-8 windows-phone windows-phone-8.1 windows-phone-8-emulator


【解决方案1】:

你会想要使用这样的东西:

<ComboBox x:Name="combobox1" ItemsSource="{Binding ItemList}">
   <ComboBox.ItemTemplate>
      <DataTemplate>
         <!-- define data template and/or style, example: -->
         <TextBlock Style="{StaticResource TextBlockItemStyle}" Text="{Binding ItemText}"/>
      </DataTemplate>
   </ComboBox.ItemTemplate>
</ComboBox>

此外,由于您想动态添加/删除项目,最好将项目源绑定到您可以在 c# 中轻松编辑的列表或集合。你可能想创建一个类:

public class ComboBoxListItem
{
   public string ItemText {get; set;}
   //any other useful property
}

然后在您的页面中创建一个List&lt;ComboBoxListItem&gt; ItemList 并在页面的构造函数中,使用您想要的任何数据初始化列表。然后在您的 XAML DataTemplate 中,只需将 "{Binding ItemText}" 插入您希望文本出现的任何位置(就像我在文本块中所做的那样)。

【讨论】:

  • 最好使用ObservableCollection 进行绑定,而不是List。 Lists 在更改时不会更新绑定,因为它们没有实现 INotifyCollectionChanged 和 INotifyPropertyChanged,但 ObservableCollections 可以。
【解决方案2】:
<ComboBox
        SelectedIndex="0"
        Foreground="Black"
        ItemContainerStyle="{StaticResource ComboBoxItemStyle1}"
        BorderBrush="Black"
        HorizontalAlignment="Left" Margin="108,280,0,0" VerticalAlignment="Top" Width="200" Style="{StaticResource ComboBoxStyl}">
        <ComboBoxItem Content="One"  />
        <ComboBoxItem Content="Two" />
        <ComboBoxItem Content="Three" />
        <ComboBoxItem Content="Four" />
        <ComboBoxItem Content="Five" />
</ComboBox>

使用引用我们为 ComboBoxItems 创建的样式表的“ItemContainerStyle”,无论是静态声明还是动态声明,我们都可以轻松更改 ComboBoxItems 的样式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 2014-09-28
    • 1970-01-01
    • 2017-08-20
    相关资源
    最近更新 更多