У меня здесь есть академический вопрос. Посмотрите на разметку:Wpf Combobox SelectionChanged event CommandParameter confuse
<Grid Margin="10,10,10,10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ComboBox SelectedIndex="{Binding SelectedIndex}"
Margin="5"
Width="100">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding TestCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ComboBox},
Path=SelectedIndex}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<ComboBoxItem>Item1</ComboBoxItem>
<ComboBoxItem>Item2</ComboBoxItem>
<ComboBoxItem>Item3</ComboBoxItem>
</ComboBox>
<Button Grid.Row="1"
Content="Set SelectedIndex to 0"
Width="100"
Command="{Binding ButtonCommand}"
Margin="5">
</Button>
</Grid>
Это DataContext
класс.
class Class1Context : ViewModelBase
{
private int _selectedIndex;
public Int32 SelectedIndex
{
get { return _selectedIndex; }
set
{
_selectedIndex = value;
RaisePropertyChanged("SelectedIndex");
}
}
private RelayCommand<Object> _testCommand;
public RelayCommand<Object> TestCommand
{
get
{
return _testCommand ?? (_testCommand =
new RelayCommand<Object>(TestMethod));
}
}
private void TestMethod(Object obj)
{
var index = (Int32) obj;
var selIndex = SelectedIndex;
}
private RelayCommand _buttonCommand;
public RelayCommand ButtonCommand
{
get
{
return _buttonCommand ?? (_buttonCommand =
new RelayCommand(ButtonCommandMethod));
}
}
private void ButtonCommandMethod()
{
SelectedIndex = 0;
}
}
Итак, в чем проблема? Вот. Когда я выбираю Item2
или Item3
, то SelectedIndex
свойство равно 1 или 2. Например, я нажал Item2
и SelectedIndex
равен 1 сейчас. Следовательно, когда я нажимаю Button
и устанавливаю SelectedIndex
в 0, он генерирует событие SelectionChanged
в Combobox
. Это логично. Затем событие запускает ограниченную команду TestCommand
. И в TestMethod
индекс (CommandParameter
) равен 1 (один!), и это проблема, несмотря на то, что SelectedIndex
из DataContext
равно 0 (ноль). Итак, это ошибка Wpf
или что-то еще?
почему вы пытаетесь справиться с поведением ComboBox дважды, IMO в сценарии выше требуется только для привязки свойства SelectedIndex. Любое поведение, которое вы хотите выполнить, должно поместить это как часть реализации сеттера. – AwkwardCoder