Binding ReactiveList to ComboBox couldn't find

2019-08-06 10:58发布

问题:

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);

Is there a simple way to force ToString() to be used for the display values?

回答1:

Regular Binding will automatically work without a DataTemplate. It will generate a DataTemplate to display a string representation of the provided data.

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>

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