【问题标题】:Issue when displaying controls显示控件时的问题
【发布时间】:2013-03-24 14:21:19
【问题描述】:

我正在尝试将标签存储在带有类别的 ComboBox 中 - 类似于 this

但是,ComboBox 项的显示如下:

这是我到目前为止所做的:

App.XAML

<DataTemplate x:Key="groupStyle">
    <Label FontWeight="Bold" Content="{Binding Name}"/>
</DataTemplate>

代码背后

    ComboBox comboBox1 = new ComboBox();

    GroupStyle style = new GroupStyle();
    style.HeaderTemplate = (DataTemplate)this.FindResource("groupStyle");
    comboBox1.GroupStyle.Add(style);
    comboBox1.DisplayMemberPath = "Item";
    ObservableCollection<CategoryItem<Label>> items = new ObservableCollection<CategoryItem<string>>();

    Label label = new Label();
    TextBlock block = new TextBlock();
    block.Text = "Text";
    label.Content = block;

    items.Add(new CategoryItem<Label> { Category = "Category", Item = label });

    CollectionViewSource cvs = new CollectionViewSource();
    cvs.GroupDescriptions.Add(new PropertyGroupDescription("Category"));
    cvs.Source = items;

    Binding b = new Binding();
    b.Source = cvs;
    BindingOperations.SetBinding(comboBox1, ComboBox.ItemsSourceProperty, b);

public class CategoryItem<T>
{
    public T Item { get; set; }
    public string Category { get; 
}

【问题讨论】:

    标签: c# .net wpf xaml data-binding


    【解决方案1】:

    您应该使用ItemContainerStyle。不过你可以看看this

    App.Xaml

    <DataTemplate x:Key="groupStyle">
        <TextBlock FontWeight="Bold" Text="{Binding Name}"/>
    </DataTemplate>
    <Style TargetType="{x:Type ComboBoxItem}"  x:Key="comboBoxItemStyle">
        <Setter Property="Template" >
            <Setter.Value>
                <ControlTemplate>
                    <Label Background="Red" Content="{Binding Item}"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    

    背后的代码:

     ComboBox comboBox1 = new ComboBox();
    
     GroupStyle style = new GroupStyle();
     style.HeaderTemplate = (DataTemplate)this.FindResource("groupStyle");
     comboBox1.GroupStyle.Add(style);
     comboBox1.DisplayMemberPath = "Item";
    
     // Here is what you are looking for
     comboBox1.ItemContainerStyle = (Style)this.FindResource("comboBoxItemStyle");
    
    
     ObservableCollection<CategoryItem<string>> items = new ObservableCollection<CategoryItem<string>>();
    
     CollectionViewSource cvs = new CollectionViewSource();
     cvs.GroupDescriptions.Add(new PropertyGroupDescription("Category"));
     cvs.Source = items;
    
     Binding b = new Binding();
     b.Source = cvs;
     BindingOperations.SetBinding(
               comboBox1, ComboBox.ItemsSourceProperty, b);
    

    【讨论】:

    • 现在唯一的问题似乎是,当我将鼠标悬停在标签上时,它们周围没有蓝色边框,就像悬停在 ComboBoxItem 上时一样
    • 我认为,您应该在ControlTemplate 中定义一些触发器,但在这种情况下我还不够好。我编辑了我的帖子,您可能会从我提供的链接中得到一些想法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多