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

时间:2011-03-14 14:36:16

标签: 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>

但是,当我在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>

事件不会触发。

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

2 个答案:

答案 0 :(得分:8)

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

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

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

干杯, 劳伦

答案 1 :(得分:0)

似乎有些事情在TextBox之前处理事件。也许你可以在ViewModel中听到Title属性(集合)的变化,因为无论如何你在触发器内调用ViewModel上的TextChanged,我想。

顺便说一下,我认为你的绑定表达中缺少TwoWay模式。

希望这有帮助。