使用ReactiveUI WPF无法绑定从ViewModel的枚举值列表,以组合OBOBOX



我有这个枚举

 public enum LogType
     {
         None = 0,
         File = 1,
         Folder = 2
     }

我有此组合曲线

    <ComboBox Name="CustomLogLogType"  FontSize="10"
              MinHeight="20" Height="20" SelectedItem="{Binding LogType}">

然后像So

这样的ViewModel
public class CustomLogRuleItemViewModel : ReactiveObject
{
    [Reactive]
    public LogType LogType { get; set; } = LogType.File;
    public List<LogType> LogTypes => Enum.GetValues(typeof(LogType)).Cast<LogType>().Where(_ => _ != LogType.None).ToList();
}

然后在View

后面的代码中
public partial class CustomLogRuleItemView : ReactiveUserControl<CustomLogRuleItemViewModel> 
{
    public CustomLogRuleItemView()
    {
        InitializeComponent();
        this.ViewModel = new CustomLogRuleItemViewModel();
        this.DataContext = this.ViewModel;
        //The below works
        //CustomLogLogType.ItemsSource = this.ViewModel.LogTypes;

        this.WhenActivated(
            disposables =>
            {
                //If I use below it will error with exception
                this.OneWayBind(this.ViewModel,
                        _ => _.LogTypes, _ => _.CustomLogLogType.ItemsSource)
                    .DisposeWith(disposables);
            });
    }
}

基本上,如果我与下面的绑定在一起

CustomLogLogType.ItemsSource = this.ViewModel.LogTypes;

但是,如果我尝试使用ReactiveUi进行绑定,如下

            this.OneWayBind(this.ViewModel,
                    _ => _.LogTypes, _ => _.CustomLogLogType.ItemsSource)
                .DisposeWith(disposables);

我得到一个例外,指出reactiveUi上的logtype违反了't'类型的约束。不确定为什么我会得到有关iViewfor的争论,因为这与查看的ViewModel实现有关。

问题是,默认情况下,ReactiveUI将通过解决IViewFor<TypeInItemsSource>来设置ItemTemplate,这旨在使您更容易拆分视图。因此,如果在这些情况下添加ItemTemplate,DisplayMember Path或ItemTemplatesElector,则自动查找将关闭。请参阅此代码的代码。

<ComboBox Name="CustomLogLogType"  FontSize="10"
                  MinHeight="20" Height="20">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}" />
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

我能够通过添加自己的ItemTemplate来解决它。

我认为这实际上是一个错误,因此,如果您不介意在https://github.com/reactiveui/reactiveui/issues上打开一个错误,我将在接下来的几天内为此进行修复。我认为对于原始类型,我们不应该添加一个itemTemplate,因为实际上我看不到用户实际上想要原始类型的功能。

最新更新