使用MVVM模式获取WPF组合框SelectedItem属性

Den*_*els -1 c# wpf mvvm

我正在将一个Observable集合绑定到combobox使用该MVVM模式.我可以成功绑定到combobox但现在我正在寻找一种方法来获取SelectedItem我的视图模型中的属性(我不能简单地调用它,因为这会制动模式)我想象的方式是必须有一些方法来创建一个绑定,XAML其中指向所选项目,我稍后可以在我的视图模型中使用.我似乎无法弄清楚的是如何...

有关如何实现这一目标的任何建议?

XAML

<ComboBox SelectedIndex="0" DisplayMemberPath="Text" ItemsSource="{Binding Path=DocumentTypeCmb,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
          Grid.Column="1" Grid.Row="4" Margin="0,4,5,5" Height="23"
          HorizontalAlignment="Left" Name="cmbDocumentType" VerticalAlignment="Bottom"
          Width="230" />
Run Code Online (Sandbox Code Playgroud)

//Obesrvable collection property
private ObservableCollection<ListHelper> documentTypeCollection = new ObservableCollection<ListHelper>();
public ObservableCollection<ListHelper> DocumentTypeCmb
{
    get
    {
        return documentTypeCollection;
    }
    set
    {
        documentTypeCollection = value;
        OnPropertyChanged("DocumentTypeCmb");
    }
}

//Extract from the method where i do the binding
documentTypeCollection.Add(new ListHelper { Text = "Item1", IsChecked = false });
documentTypeCollection.Add(new ListHelper { Text = "Item2", IsChecked = false });
documentTypeCollection.Add(new ListHelper { Text = "Item3", IsChecked = false });

DocumentTypeCmb = documentTypeCollection; 

//Helper class
public class ListHelper
{
    public string Text { get; set; }
    public bool IsChecked { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

slu*_*ter 8

试试这个:

public ListHelper MySelectedItem { get; set; }
Run Code Online (Sandbox Code Playgroud)

和XAML:

<ComboBox ItemsSource="{Binding Path=DocumentTypeCmb,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
      SelectedItem={Binding MySelectedItem}
      />
Run Code Online (Sandbox Code Playgroud)

您只需要在ViewModel中拥有一个获取/设置正确类型的公共属性,然后使用绑定将所选项目分配给它.请注意,SelectedItem是一个依赖项proeprty,因此您可以像这样绑定,但是对于列表控件SelectedItems(注意复数)不是依赖项属性,因此您无法将其绑定回VM - 为此,有一个简单的解决方法可供使用而是一种行为.

另请注意,我没有在我的示例中实现属性更改通知,因此如果您从VM更改所选项目,它将不会在UI中更新,但这是微不足道的.

  • +1,但是在设置itemssource时请摆脱Mode = TwoWay - 只是毫无意义. (2认同)