MVVM Light工具包Interaction.Triggers不会在datatemplate中触发

fer*_*rgs 2 mvvm-light

我可以使用Interaction.Triggers来捕获文本框上的textchanged事件,如下所示:

<TextBox  Text="{Binding Title}" Style="{StaticResource GridEditStyle}">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="TextChanged">
                            <cmd:EventToCommand Command="{Binding TextChanged}" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </TextBox>
Run Code Online (Sandbox Code Playgroud)

但是,当我在listate celltemplate的datatemplate中使用它时,如下所示:

 <ListView  ItemsSource="{Binding LangaugeCollection}" SelectedItem="{Binding SelectedLangauge}" BorderThickness="0" FontFamily="Calibri" FontSize="11">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Width="200">
                            <GridViewColumn.CellTemplate>
                                <DataTemplate >
                                    <Grid>
                                        <TextBlock Text="{Binding Title}" Style="{StaticResource GridBlockStyle}">
                                        </TextBlock>
                                        <TextBox  Text="{Binding Title}" Style="{StaticResource GridEditStyle}">
                                            <i:Interaction.Triggers>
                                                <i:EventTrigger EventName="TextChanged">
                                                    <cmd:EventToCommand Command="{Binding TextChanged}" />
                                                </i:EventTrigger>
                                            </i:Interaction.Triggers>
                                        </TextBox>
                                    </Grid>
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                    </GridView> 
                </ListView.View>
            </ListView>
Run Code Online (Sandbox Code Playgroud)

该事件不会触发.

有谁知道为什么这不会触发以及如何解决它?

LBu*_*ion 8

当您在DataTemplate中时,DataContext可能不是您所期望的.通常,DataTemplate中的DataContext设置为DataTemplate表示的项.如果TextChanged命令位于"主视图模型"而不是数据项上,则需要更精确地指定数据绑定,例如:

Command ="{Binding Source = {StaticResource Locator},Path = Main.TextChanged}"

在Studio中以调试模式(F5)运行代码并观察"输出"窗口时,可以看到问题.如果DataContext设置不正确,将显示数据错误.

干杯,洛朗