【问题标题】:Bind property from element in ItemsSource to Label Content将 ItemsSource 中元素的属性绑定到标签内容
【发布时间】:2015-11-24 14:08:33
【问题描述】:

我已经创建了自己的用户控件。此控件有自己的属性ItemsSource,类型为Dictionary<string, object>。键 - 它是我绑定到 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));
        }
    }

}

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

【问题讨论】:

  • 你不能绑定到Value.Description吗?
  • @AntiHeadshot,不...价值无法识别
  • 你能添加一个 XAML sn-p

标签: c# wpf xaml binding


【解决方案1】:

你必须设置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>

【讨论】:

  • 键和值不返回任何东西
  • @demo Books 的类型为 Dictionary&lt;string,Book&gt;,您在输出中看到任何绑定错误吗?
  • @demo 所以你的输出窗口中没有像System.Windows.Data Error: 40 : BindingExpression path error: 这样的行?
  • @demo 我下载了演示文件并尝试绑定到SelectedItems,看来Multiselect 没有正确更新属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-22
  • 1970-01-01
相关资源
最近更新 更多