ComboBox与ReactiveUI绑定ItemsSource时必须定义ComboBox.ItemTemplate。

问题描述 投票:0回答:1

我用的是 反应式UI 在我的项目中,我用它来绑定一个新的项目。ObservableCollectionComboBox.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();
    }
}

HomeView.xaml

<VirtualizingStackPanel>
    <ComboBox Name="CountriesComboBox">

    </ComboBox>
</VirtualizingStackPanel>

当我打开应用程序并点击 ComboBox抛出了一个异常。enter image description here

我定义了 项目模板ComboBox.ItemTemplate,ComboBox成功运行。

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

我的问题是,我可以在不定义默认模板的情况下使用集合绑定吗?

  • 我可以在不定义默认模板的情况下使用集合绑定吗?
c# wpf dynamic-data reactiveui
1个回答
0
投票

而不是绑定到 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="." />
© www.soinside.com 2019 - 2024. All rights reserved.