ListBox中的ComboBox不会触发SelectionChanged事件

时间:2012-01-05 17:06:40

标签: c# wpf xaml mvvm

我有一个wpf,mvvm应用程序,使用catel(http://catel.codeplex.com)framework \ toolkit,C#.Net 4.0。该应用程序有一个带有TextBlock和ComboBox的ListBox。 ListBox和ComboBox由ViewModel中的2个不同的ObservableCollection填充。当用户单击按钮时,我需要保存(到数据库),ListBox中用户从ComboBox中选择项目的每一行。 SelectionBox函数中的任何ComboBox都不会触发SelectionChanged事件。想法是我在ViewModel中添加一个列表(ArrayList或IList?),每次用户选择一个ComboBox中的项目以及该项目被选中的行。

或者我是否通过尝试使用ComboBoxe SelectionChanged事件来解决这个问题?我也尝试通过ListBox.Items进行迭代,但这似乎是一个hak,如果可能的话我想在ViewModel中避免使用ui元素逻辑。

xaml:

<Grid>
<StackPanel Orientation="Horizontal">
    <Label Width="180">Field1</Label>
    <ListBox Height="200" 
            IsSynchronizedWithCurrentItem="True" 
            ItemsSource="{Binding List1, Mode=OneWay}" 
            Name="listBox1" 
            SelectionMode="Single" 
            Width="300">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal" Width="290">
                    <TextBlock Width="90" Text="{Binding}"></TextBlock>
                        <ComboBox Width="180" ItemsSource="{Binding DataContext.List2, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}" DisplayMemberPath="Field1">
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="SelectionChanged">
                                    <catel:EventToCommand Command="{Binding SelectionChangedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" DisableAssociatedObjectOnCannotExecute="False" PassEventArgsToCommand="True" />
                                </i:EventTrigger>
                            </i:Interaction.Triggers>
                        </ComboBox>
                    </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</StackPanel>

ViewModel代码:

//in the ViewModel constructor

SelectionChangedCommand = new Command<SelectionChangedEventArgs>(OnSelectionChangedCommandExecute, OnSelectionChangedCommandCanExecute);



public Command<SelectionChangedEventArgs> SelectionChangedCommand { get; private set; }

private bool OnSelectionChangedCommandCanExecute()
{
    return true;
}

private void OnSelectionChangedCommandExecute(SelectionChangedEventArgs e)
{
    // add or update list....
}

1 个答案:

答案 0 :(得分:3)

在Command绑定中,您使用了具有相对源绑定的绑定...

考虑在绑定中进行这些更改

1)使用列表框作为Ancestortype

2)绑定时使用Path = DataContext.SelectionChangedCommand,否则它将把列表框作为datacontext。

<catel:EventToCommand Command="{Binding Path=DataContext.SelectionChangedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" DisableAssociatedObjectOnCannotExecute="False" PassEventArgsToCommand="True" />