簡體   English   中英

ComboBox 在將 ItemsSource 與 ReactiveUI 綁定時必須定義 ComboBox.ItemTemplate

[英]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時,拋出異常: 在此處輸入圖像描述

我在ComboBox.ItemTemplate中定義了ItemTemplate , ComboBox 工作成功。

<ComboBox Name="CountriesComboBox">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

我的問題是:

  • 我可以在不為 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM