在ItemTemplate选择上添加命令

时间:2012-10-12 09:47:17

标签: c# wpf click itemtemplate

我认为这是一个非常简单的问题,但我找不到答案。我有一个itemtemplate定义到datatemplate。当选择一个项目时,我想触发一个命令来选择我的元素的名称并将其应用到其他地方。目前,MouseDown事件不接受我的命令。

<ListView Margin="4" Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding Path=ExistingStateInfos, ElementName=Window}"
                  SelectedItem="{Binding Path=SelectedStateInfo, ElementName=Window}" x:Name="statinfoListview">
            <ListView.ItemTemplate>
                <DataTemplate DataType="{x:Type States:StateInfo}">
                    <TextBlock Text="{Binding Path=Name}" MouseDown="{x:Static MyWindow.ApplyStateInfoNameToStateCommand}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

2 个答案:

答案 0 :(得分:0)

您无法直接将命令设置为事件处理程序。

使用MVVM LightToolkit

中的EventToCommand
<DataTemplate DataType="{x:Type States:StateInfo}">
    <TextBlock Text="{Binding Path=Name}">
       <i:Interaction.Triggers>
         <i:EventTrigger EventName="MouseDown">
            <Command:EventToCommand Command="{Binding YourCommand, Mode=OneWay}" />
         </i:EventTrigger>
       </i:Interaction.Triggers>
    </TextBlock>
 </DataTemplate>

答案 1 :(得分:0)

实际上ot是我的漏洞,我只是添加来做

<TextBlock Text="{Binding Path=Name}" MouseDown="{x:Static ApplyStateInfoNameToState_Click}" />

对不起,这是星期五。祝周末愉快:)