将 ReactiveList 绑定到 ComboBox 找不到视图错误 [英] Binding ReactiveList to ComboBox couldn't find view error
问题描述
我将 ReactiveList 绑定到视图代码隐藏中的 ComboBox 并收到错误 System.Exception: 'Couldn't find view for 'Value1'.'.
I am binding a ReactiveList to a ComboBox in the view code-behind and get the error System.Exception: 'Couldn't find view for 'Value1'.'.
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()
用于显示值?
Is there a simple way to force ToString()
to be used for the display values?
推荐答案
Regular Binding
将在没有 DataTemplate
的情况下自动工作.它将生成一个 DataTemplate
以显示所提供数据的 string
表示.
Regular Binding
will automatically work without a DataTemplate
. It will generate a DataTemplate
to display a string
representation of the provided data.
RxUI 绑定不能那样工作;你必须提供一个 DataTemplate
才能让它们工作:
RxUI bindings does not work that way; you have to provide a DataTemplate
for them to work:
<ComboBox Name="Source">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
当只使用 {Binding}
时,它应该回退到在您的类上调用 ToString()
.或者,您当然可以告诉它手动绑定到 Name
属性:
When just using {Binding}
it should fall back to calling ToString()
on your class. Alternatively you can of course tell it to bind to the Name
property manually:
<TextBlock Text="{Binding Name}"/>
这篇关于将 ReactiveList 绑定到 ComboBox 找不到视图错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!