我将ReactiveList绑定到视图代码隐藏中的ComboBox并获取错误 System.Exception:'找不到' Value1'的视图。& #39;
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);
是否有一种简单的方法可以强制ToString()
用于显示值?
答案 0 :(得分:5)
常规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}"/>