繁体   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