2015-11-24 88 views
2

我已經創建了自己的UserControl。該控件擁有Dictionary<string, object>類型的ItemsSource自己的屬性。鍵 - 它是我綁定到ItemsSource的集合中的元素的標題。將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); 

所以我想訪問Description,如果我剛纔ItemsSource。可能嗎?


我的用戶是一樣的在這裏MultipleComboBox

書面和我綁定的ItemsSource這樣的:

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

我的解決方案,我能想象 - 添加屬性類節點,它將使用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)); 
     } 
    } 

} 

但它是很好的解決方案?從性能方面來說。由於

+0

你就不能綁定到'Value.Description'? – AntiHeadshot

+0

@AntiHeadshot,nope ...價值不可識別 – demo

+0

是否可以添加XAML摘要 – AntiHeadshot

回答

0

您必須設置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> 
+0

Key和Value不會返回任何內容 – demo

+0

@demo Books的類型是'Dictionary ',您是否在輸出中看到任何綁定錯誤? – AntiHeadshot

+0

沒有錯誤,只是沒有顯示 – demo