[英]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.