将ReactiveList绑定到ComboBox无法找到视图错误

时间:2017-07-16 21:03:37

标签: wpf reactiveui

我将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()用于显示值?

1 个答案:

答案 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}"/>