[英]ComboBox must define ComboBox.ItemTemplate when binding ItemsSource with ReactiveUI
我正在为我的项目使用Reactive UI 。 我使用它将ObservableCollection绑定到ComboBox.ItemsSource 。 以下是我正在做的事情:
HomeViewModel.cs
public class HomeViewModel : ReactiveObject, IRoutableViewModel
{
#region Properties
public string UrlPathSegment => "HOME";
public IScreen HostScreen => null;
private SourceList<int> _myList { get; } = new SourceList<int>();
private readonly IObservableCollection<int> _targetCollection = new ObservableCollectionExtended<int>();
public IObservableCollection<int> TargetCollection => _targetCollection;
#endregion
public HomeViewModel()
{
Task.Run(() =>
{
for (int i = 0; i < 100; ++i)
{
_myList.Add(i);
System.Threading.Thread.Sleep(500);
}
});
_myList.Connect()
.ObserveOnDispatcher()
.Bind(_targetCollection)
.Subscribe();
}
}
主页查看.xaml
<VirtualizingStackPanel>
<ComboBox Name="CountriesComboBox">
</ComboBox>
</VirtualizingStackPanel>
我在ComboBox.ItemTemplate中定义了ItemTemplate , ComboBox 工作成功。
<ComboBox Name="CountriesComboBox">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
我的问题是:
而不是像这样在视图的代码隐藏中绑定到ItemsSource
属性,如下所示:
this.OneWayBind(ViewModel, x => x.TargetCollection, v => v.CountriesComboBox.ItemsSource);
...您可以使用内置标记扩展将其绑定到 XAML 标记中:
<ComboBox Name="CountriesComboBox" ItemsSource="{Binding TargetCollection, Mode=OneTime}">
然后,您可以以牺牲一些编译时安全性为代价摆脱ItemTemplate
。
另一个选项是设置DisplayMemberPath
而不是ItemTemplate
属性并保持对OneWayBind
的调用:
<ComboBox Name="CountriesComboBox" DisplayMemberPath="." />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.