如何将ReactiveList <someobject>绑定到WPF ListBox或ListView?</someobject>

时间:2014-08-20 12:59:07

标签: reactiveui

我有一个简单的ViewModel:

public class SampleCollectionViewModel : ReactiveObject
    {
        public SampleCollectionViewModel()
        {
            this.Countries = new ReactiveList<Country>();
            this.Countries.Add(new Country { Name = "Andora" });
            this.Countries.Add(new Country { Name = "Aruba" });
            this.Countries.Add(new Country { Name = "Afganistan" });
            this.Countries.Add(new Country { Name = "Algeria" });
            this.Countries.Add(new Country { Name = "Argentina" });
            this.Countries.Add(new Country { Name = "Armenia" });
            this.Countries.Add(new Country { Name = "Antigua" });    
            //CountryNames.AddRange(this.Countries.Select(x => x.Name));
        }

        public ReactiveList<Country> Countries { get; set; }
        //public ReactiveList<string> CountryNames { get; set; }
    }

和一个简单的视图:

public partial class SampleCollectionWindow : Window, IViewFor<SampleCollectionViewModel>
    {
        public SampleCollectionWindow()
        {
            InitializeComponent();

            this.ViewModel = new SampleCollectionViewModel();


            this.Bind(ViewModel, vm => vm.Countries, v => v.CountriesListBox.ItemsSource);
        }

        public SampleCollectionViewModel ViewModel { get; set; }

        object IViewFor.ViewModel
        {
            get { return ViewModel; }
            set { ViewModel = (SampleCollectionViewModel)value; }
        }
    }

当我运行它时,我得到:  exception Additional information: Can't two-way convert between ReactiveUI.ReactiveList``1[DemoReactiveUiWpf.SampleCollection.Country] and System.Collections.IEnumerable. To fix this, register a IBindingTypeConverter

如果我改变了 this.Bind(ViewModel, vm => vm.Countries, v => v.CountriesListBox.ItemsSource);this.OneWayBind(ViewModel, vm => vm.Countries, v => v.CountriesListBox.ItemsSource); ListBox

没有任何反应

稍后我将扩展这个简单的演示,使用命令和异步命令将新国家/地区添加到模型中。

删除ListBox / ListView条目中的所选内容。

尝试过滤,排序和ReactiveUI提供的其他有趣操作。

但就目前而言,我不能做简单的绑定......

如何将ListBox / ListView绑定到ReactiveList<Country>并以正确的方式对ReactiveList + ListBox / ListView执行常见操作?

谢谢!

1 个答案:

答案 0 :(得分:4)

您绝对不能使用双向绑定绑定到ItemsSource - 正如错误消息所示,您无法保证设置ListBox.ItemsSource的某人将使用ReactiveList<Country>。这适用于我的机器:

this.OneWayBind(ViewModel, x => x.Countries, x => x.countries.ItemsSource);
  

... ListBox

没有任何反应

我想知道你是否也没有配置DataTemplate? ReactiveUI使用ViewModelViewHost覆盖默认DataTemplates(因为您很可能没有为Country注册View,它会失败)。

更新:以下是我如何绑定SelectedItems,将其放入视图中:

this.WhenAnyValue(x => x.countries.SelectedItems)
    .Select(list => list.Cast<Country>())
    .BindTo(this, x => x.ViewModel.SelectedCountries);