WPF Combobox SelectedIndex属性绑定不起作用

时间:2012-11-15 00:44:56

标签: wpf wpf-4.0

我正在尝试将combobox的SelectedIndex属性绑定到我的ViewModel。这是代码。

的Xaml:

<ComboBox x:Name="BloodGroupFilter" SelectedIndex="{Binding Path=SelectedBloodGroupIndex, Mode=TwoWay}">
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ComboBoxItem Foreground="red" FontStyle="Italic">No Filter</ComboBoxItem>
            <CollectionContainer Collection="{Binding Source={StaticResource BloodGroupEnum}}"/>
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

视图模型

private int _selectedBloodGroupIndex = 4;
public int SelectedBloodGroupIndex {
    get { return _selectedBloodGroupIndex; }
    set { 
        _selectedBloodGroupIndex = value; 
    }
}

正如您所看到的,我正在尝试将组合框的SelectedIndex设置为“4”。这不会发生,并且SelectedIndex设置为0.此外,当用户选择组合框的特定项时,我期望ViewModel的SelectedBloodGroupIndex属性将自己更新为当前选择的组合框项目,但这不会发生。永远不会调用ViewModel属性(set和get)。上述代码绑定失败的任何原因。

更新

<UserControl.Resources>
    <ObjectDataProvider x:Key="BloodGroupEnum" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="enums:BloodGroup" />
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</UserControl.Resources>

1 个答案:

答案 0 :(得分:2)

您需要在ViewModel的 SelectedBloodGroupIndex 的setter中更改Notify属性。我希望你有关于PropertyChanged事件的想法。

<Window x:Class="WpfApplication4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:myWindow="clr-namespace:WpfApplication4"
    Title="MainWindow" Height="800" Width="800" WindowStartupLocation="CenterScreen">

<Grid>
    <ComboBox SelectedIndex="{Binding SelectedIndex}">
        <ComboBoxItem Content="1"/>
        <ComboBoxItem Content="2"/>
        <ComboBoxItem Content="3"/>
        <ComboBoxItem Content="4"/>
        <ComboBoxItem Content="5"/>
    </ComboBox>
</Grid>

 public partial class MainWindow :Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MyViewModel();
    }
}

public class MyViewModel :INotifyPropertyChanged
{
    public MyViewModel()
    {
        SelectedIndex = 2;
    }
    private int _selectedIndex;
    public int SelectedIndex 
    { 
        get
        {
            return _selectedIndex;
        }
        set
        {
            _selectedIndex = value;
            Notify("SelectedIndex");
        }
  }

    public event PropertyChangedEventHandler PropertyChanged;

    private void Notify(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}