无法将视图框选择的索引从视图更新到viewmodel

时间:2014-02-24 21:58:49

标签: wpf c#-4.0 mvvm combobox

使用MVVM模式,我将组合框的SelectedIndex属性绑定到视图模型中的变量。我可以从视图模型中以编程方式更改组合框选择;但是,当用户从界面(视图)中进行选择时,视图模型变量不会更新。

这是XAML(snipet):

<ComboBox Width="100" HorizontalContentAlignment="Center" SelectedIndex="{Binding GroupSortIndex,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"> <ComboBoxItem Content="Appearance"/> <ComboBoxItem Content="Created"/> <ComboBoxItem Content="Name"/> </ComboBox>

以下是视图模型的一部分:

public int GroupSortIndex { get { return (int)GetValue(GroupSortIndexProperty); } set { SetValue(GroupSortIndexProperty, value); } } public static readonly DependencyProperty GroupSortIndexProperty = DependencyProperty.Register("GroupSortIndex", typeof(int), typeof(MainWindowViewModel), new UIPropertyMetadata(-1));

当用户从IU中进行选择时,我需要做些什么来更新GroupSortIndex?

1 个答案:

答案 0 :(得分:0)

是的,SelectedIndex属性看起来有一个错误。我是这个问题,我通过将SelectedIndex更改为SelectedItem来解决这个问题。

将XAML SelectedIndex更改为SelectedItem:

<ComboBox ItemsSource="{Binding Path=YourOptionsList}" 
          SelectedItem="{Binding SelectedOption}" /> 

在某处你必须设置窗口的DataContext以引用XAML中的集合。

并在ViewModel中写下这个:

public List<String> YourOptionsList { get { return (int)GetValue(YourOptionsListProperty); } set { SetValue(YourOptionsListProperty, value); } }
 public static readonly DependencyProperty YourOptionsListProperty = DependencyProperty.Register("YourOptionsList", typeof(List<String>), typeof(MainWindowViewModel), new UIPropertyMetadata(new List<String>()));

public string SelectedOption { get { return (int)GetValue(SelectedOptionProperty); } set { SetValue(SelectedOptionProperty, value); } }
 public static readonly DependencyProperty SelectedOptionProperty = DependencyProperty.Register("SelectedOption", typeof(String), typeof(MainWindowViewModel), new UIPropertyMetadata("none");


  public MainWindowViewModel()
  {
    YourOptionsList =new List<String>();
    YourOptionsList.Add("Appearance");
    YourOptionsList.Add("Created");
    YourOptionsList.Add("Name");
  }