ReactiveUI + WPF:绑定到 'ItemsSource' 未按预期工作

ReactiveUI + WPF: Binding to 'ItemsSource' not working as expected

我无法使用 ReactiveUI 和 WPF 绑定到 ListBoxComboBoxItemsSource 属性(UWP 没有问题) .或者更准确地说,绑定似乎有效,因为 ItemsSource 确实得到了填充,但 UI 没有正确显示值。

让我举个例子。我创建了一个新的 WPF 项目(使用 VS 2019)并添加了 ReactiveUI 9.16.6 NuGet。我的项目包含这些简单的文件:

MainWindow.xaml:

<reactiveui:ReactiveWindow 
        x:Class="Demo.MainWindow"
        x:TypeArguments="vms:MainViewModel"
        xmlns:vms="clr-namespace:Demo"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:reactiveui="http://reactiveui.net"
        xmlns:local="clr-namespace:Demo"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ListBox x:Name="demoList"/>
    </Grid>
</reactiveui:ReactiveWindow>

MainWindow.xaml.cs:

using ReactiveUI;
using System.Reactive.Disposables;

namespace Demo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : ReactiveWindow<MainViewModel>
    {
        public MainWindow()
        {
            InitializeComponent();
            ViewModel = new MainViewModel();

            // This works, UI shows "foo" and "bar"
            //demoList.ItemsSource = ViewModel.SomeList;

            this.WhenActivated(disposables =>
            {
                // This doesn't, UI shows two empty items
                this.OneWayBind(ViewModel, viewModel => viewModel.SomeList, view => view.demoList.ItemsSource)
                    .DisposeWith(disposables);
            });
        }
    }
}

MainViewModel.cs:

using ReactiveUI;
using System.Collections.Generic;

namespace Demo
{
    public class MainViewModel : ReactiveObject
    {
        public IEnumerable<string> SomeList => new List<string> { "foo", "bar" };
    }
}

这是结果: screenshot

我做错了什么?

默认情况下,WPF ReactiveUI 会为您注册一个 ItemTemplate,除非 您可以通过指定 ItemTemplateItemTemplateSelectorDisplayMemberPath 来覆盖它。源代码见 https://github.com/reactiveui/ReactiveUI/blob/1c45ce3079849c863e99bae3ee315a79ac672add/src/ReactiveUI/Platforms/windows-common/AutoDataTemplateBindingHook.cs#L87