【问题标题】:Cannot update combobox selected index from the view to the viewmodel无法将组合框选定索引从视图更新到视图模型
【发布时间】:2014-02-24 21:58:48
【问题描述】:

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

这是 XAML(片段):

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

【问题讨论】:

    标签: wpf c#-4.0 mvvm combobox


    【解决方案1】:

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

    将 XAML SelectedIndex 更改为 SelectedItem:

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

    您必须在某处设置 Window 的 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");
      }
    

    【讨论】:

    • 我几乎对你的第一点投了赞成票,但后来我注意到你的错误,然后我差点给你投了反对票。因此,我决定我不会以任何一种方式投票,但您最好在有人拒绝您的答案之前修复您的代码示例。它不会像现在这样工作,因为 SelectedOptionint 并且集合项是 strings。
    • 我必须通过ItemsSourceComboBox 绑定到一个集合。在我最初的问题中,我定义了ComboBoxItems,它不适用于SelectedIndex。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    相关资源
    最近更新 更多