ReactiveUI + WPF:绑定到“ ItemsSource”不能按预期工作

时间:2019-06-06 09:05:37

标签: c# wpf reactiveui

我无法使用ReactiveUI和WPF绑定到ItemsSourceListBox的{​​{1}}属性(UWP没问题)。或者更确切地说,绑定似乎在填充ComboBox时起作用,但是UI无法正确显示值。

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

MainWindow.xaml

ItemsSource

MainWindow.xaml.cs

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

MainViewModel.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);
            });
        }
    }
}

这是结果: screenshot

我在这里做什么错了?

1 个答案:

答案 0 :(得分:0)

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