gpt4 book ai didi

reactiveui - 如何将 ReactiveList 绑定(bind)到 WPF ListBox 或 ListView?

转载 作者:行者123 更新时间:2023-12-02 21:24:43 27 4
gpt4 key购买 nike

我有一个简单的 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; }
}

和一个简单的 View :

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 提供的过滤、排序和其他有趣的操作。

但目前我还无法进行简单的绑定(bind)...

如何绑定(bind)ListBox/ListViewReactiveList<Country>并以正确的方式使用ReactiveList + ListBox/ListView进行常见操作?

谢谢!

最佳答案

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

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

...nothing happens with ListBox

我想知道您是否没有配置DataTemplate? ReactiveUI 使用 ViewModelViewHost 覆盖默认的 DataTemplates (并且由于您很可能没有为国家/地区注册 View ,因此它会失败)。

更新:这是我绑定(bind) SelectedItems 的方法,将其放入 View 中:

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

关于reactiveui - 如何将 ReactiveList<SomeObject> 绑定(bind)到 WPF ListBox 或 ListView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25405394/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com