2017-07-16 32 views
0

我將ReactiveList綁定到視圖代碼隱藏中的ComboBox並獲取錯誤System.Exception:'無法找到'Value1'的視圖。將ReactiveList綁定到ComboBox無法找到視圖錯誤

ViewModel.cs

public class SourceItem 
{ 
    public override string ToString() 
    { 
     return Name; 
    } 
    public string Name { get; set; } 
} 

public class ViewModel : ReactiveObject 
{ 
    public ReactiveList<SourceItem> SourceList { get; } = new ReactiveList<SourceItem>(); 
    public SourceItem SelectedSourceItem { get; set; } 

    public ViewModel() 
    { 
     SourceList.Add(new SourceItem() {Name = "Value1"}); 
    } 
} 

View.xaml

<ComboBox Name="Source"/> 

View.cs

this.OneWayBind(ViewModel, x => x.SourceList, x => x.Source.ItemSource); 
this.Bind(ViewModel, x => x.SelectedSourceItem, x => x.Source.SelectedItem); 

是否有SIMP le方式強制ToString()用於顯示值?

+0

您需要DataTemplate for ComboBox – Coding4Fun

回答

3

定期Binding將自動工作,沒有DataTemplate。它將生成一個DataTemplate來顯示所提供數據的表示形式string

RxUI綁定不起作用;你必須爲他們提供一個DataTemplate工作:

<ComboBox Name="Source"> 
    <ComboBox.ItemTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding}"/> 
     </DataTemplate> 
    </ComboBox.ItemTemplate> 
</ComboBox> 

如果只是用{Binding}應該退回到您的通話類ToString()。或者,您可以告訴它手動綁定到Name屬性:

<TextBlock Text="{Binding Name}"/>