将ItemsSource中元素的属性绑定到Label Content

本文关键字:绑定 Label Content 属性 ItemsSource 元素 | 更新日期: 2023-09-27 18:24:11

我已经创建了自己的UserControl。此控件具有自己的Dictionary<string, object>类型的属性ItemsSource。Key—它是集合中元素的Title,我将其绑定到ItemsSource。

我可以访问ItemsSource的任何属性而不将其值单独添加到ItemsSource吗(不要转换为List<Tuple<string, string, object>>


public class Book
{
   public int Id{get;set}
   public string Title{get;set;}
   public string Description{get;set;}
}
var list = new List<Book>(){//initializing};
userControl.ItemsSource = list.ToDictionary(i => i.Title, i => i);

所以如果我只有ItemsSource,我想访问Description。有可能吗?


我的UserControl与此处所写的MultipleComboBox 相同

我像这样绑定ItemsSource:

<controls:MultiSelectComboBox SelectedItems="{Binding SelectedBooks, Mode=TwoWay}" x:Name="Books" DefaultText="Category" ItemsSource="{Binding Books}"/>

我可以想象的解决方案-将属性添加到类Node,该类将使用ItemsSource的Value属性初始化。在它像Value.Description.那样绑定之后

公共类节点:INotifyPropertyChanged{

    private string _title;
    private object _value;
    private bool _isSelected;
    #region ctor
    public Node(string title, object value)
    {
        Title = title;
        Value = value;
    }
    #endregion
    #region Properties
    public string Title
    {
        get
        {
            return _title;
        }
        set
        {
            _title = value;
            NotifyPropertyChanged("Title");
        }
    }
    public object Value
    {
        get { return _value; }
        set
        {
            _value = value;
            NotifyPropertyChanged("Value");
        }
    }
    public bool IsSelected
    {
        get
        {
            return _isSelected;
        }
        set
        {
            _isSelected = value;
            NotifyPropertyChanged("IsSelected");
        }
    }
    #endregion
    public event PropertyChangedEventHandler PropertyChanged;
    protected void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

但这是一个好的解决方案吗?从性能方面来看。感谢

将ItemsSource中元素的属性绑定到Label Content

您必须设置ItemTemplate

<ComboBox ItemsSource="{Binding Books}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Key}"/>
                <TextBlock Text="{Binding Value.Description}"/>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>