使用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?
发布于 2014-02-24 14:28:56
是的,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");
}
https://stackoverflow.com/questions/21999953
复制