2014-07-15 6 views
1

У меня здесь есть академический вопрос. Посмотрите на разметку: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 или что-то еще?

+1

почему вы пытаетесь справиться с поведением ComboBox дважды, IMO в сценарии выше требуется только для привязки свойства SelectedIndex. Любое поведение, которое вы хотите выполнить, должно поместить это как часть реализации сеттера. – AwkwardCoder

ответ

-1

  <i:EventTrigger EventName="SelectionChanged"> 
       <i:InvokeCommandAction Command="{Binding TestCommand}" ></i:InvokeCommandAction> 
      </i:EventTrigger> 
     </i:Interaction.Triggers> 
0

Я сделал это так:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 


<ComboBox> 
         <ComboBox.Items> 
          <ComboBoxItem Content="item1" > 
           <i:Interaction.Triggers> 
            <i:EventTrigger EventName="Selected"> 
             <i:InvokeCommandAction Command="{Binding item1Cmd}"/> 
            </i:EventTrigger> 
           </i:Interaction.Triggers> 
          </ComboBoxItem> 
          <ComboBoxItem Content="item2" > 
           <i:Interaction.Triggers> 
            <i:EventTrigger EventName="Selected"> 
             <i:InvokeCommandAction Command="{Binding item2Cmd}"/> 
            </i:EventTrigger> 
           </i:Interaction.Triggers> 
          </ComboBoxItem> 
          <ComboBoxItem Content="item3" > 
           <i:Interaction.Triggers> 
            <i:EventTrigger EventName="Selected"> 
             <i:InvokeCommandAction Command="{Binding item3Cmd}"/> 
            </i:EventTrigger> 
           </i:Interaction.Triggers> 
          </ComboBoxItem> 
         </ComboBox.Items> 
        </ComboBox> 

Этот способ работал хорошо для меня. Я знаю немного накладных расходов кода, используя тот же код для каждого ComboBoxItems.

Если ComboBox будет нужен динамическую нагрузку, то вы должны быть в состоянии добавить Interaction.Triggers в код

Смежные вопросы