使用 ReactiveUI 绑定到组合框中的选定项目

Binding to selected item in combobox using ReactiveUI

我正在尝试从组合框中获取所选项目并将值发送到我的 ViewModel。如果我将绑定对象转换为组合框然后在 ViewModel 中检索标签,它会起作用,这似乎不是最好的方法,因为我也想使它成为双向绑定。

这是我在视图中的组合框

<ComboBox Name="Grade">
   <ComboBoxItem Tag="White">
       <Image Source="/Assets/Belts/White.png"/>
   </ComboBoxItem>
   <ComboBoxItem Tag="White_1">
        <Image Source="/Assets/Belts/White_1.png"/>
   </ComboBoxItem>
</ComboBox>

这是我使用 reactiveUI 进行绑定的隐藏代码

this.Bind(this.ViewModel, 
          x => x.SelectedGrade, 
          x => (ComboBoxItem) x.Grado.SelectedItem)
          .DisposeWith(disposable);

这很好用,但只有一种方法。

问题是如何检索组合框的标签?

我已经尝试过

this.Bind(this.ViewModel, 
          x => x.SelectedGrade, 
          x => x.Grado.SelectedItem.Tag)
          .DisposeWith(disposable);

还使用了 .ToString(),还尝试了 selectedValue,但似乎没有任何效果。

您需要将 Grado.ItemSource 绑定到包含您的数据的集合,否则您将没有要 select 的项目。

this.OneWayBind(ViewModel, vm => vm.Grades, view => view.Grado.ItemSource)

理想情况下,您应该从 Tag 模型转向 MVVM

SelectedItem 将始终为空,因为您没有使用 ItemSource。使用 ComboBoxItem 是一种不好的做法。您可以将您的成绩抽象为 class,然后绑定到 ItemSource。那么您的 SelectedItem 属性 将不会为 null

public class Grade 
{
   public string ImageName { get; set; }
   public BitmapSource ImageSource => BitmapImage(new Uri($"pack://application:,,,/AssemblyName;component/{ImageName}")); 
}

在你看来现在做

this.Bind(this, vm => vm.SelectedItem, view => view.combo.SelectedItem);
this.OneWayBindBind(this, vm => vm.Grades, view => view.combo.ItemsSource);