2

I am trying to bind the SelectedIndex property of combobox to my ViewModel. Here is the code.

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>

ViewModel

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

As you can see I am trying to set the SelectedIndex of combobox to "4". This doesn't happen and SelectedIndex is set to 0. Also, when user selects a particular item of the combobox, I was expecting that the ViewModel's SelectedBloodGroupIndex property will update itself to the currently selected item of combobox, but this doesn't happen either. The ViewModel property is never invoked(both set and get). Any reasons why binding is failing for the above code.

Update

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

1 回答 1

4

您需要在ViewModel的SelectedBloodGroupIndex的设置器中更改通知属性。我希望您确实对 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));
    }
}
于 2012-11-15T06:04:28.607 回答