ListBox中不同事件的不同命令

时间:2014-07-04 22:51:37

标签: c# .net mvvm listbox mvvm-light

我有以下ListBox:

<ListBox ItemsSource="{Binding CityList}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock x:name="Name" Text="{Binding Name }" />
                <TextBlock x:name="Country" Text="{Binding  Country}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

以下文章非常好地解释了如何实现SelectionChanged:

<phone:LongListSelector x:Name="Results" Margin="0,0,-12,0" ItemsSource="{Binding Events}" SelectedItem="{Binding Event}">
    <phone:LongListSelector.ItemTemplate>
        <DataTemplate>
            <StackPanel Margin="0,0,0,17">
                <TextBlock Text="{Binding benchmark.name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                <TextBlock Text="{Binding summary}" TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}"/>
            </StackPanel>
        </DataTemplate>
    </phone:LongListSelector.ItemTemplate>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Tap">
            <command:EventToCommand Command="{Binding WodSelectedCommand, Mode=OneWay}" CommandParameter="{Binding Path=SelectedItem, ElementName=Results}" PassEventArgsToCommand="False"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</phone:LongListSelector>

但是在这个示例中,Selection Changed对于我的示例中的每个Textblock都是相同的,我希望我的两个文本块有两个不同的命令。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

将事件触发器放在DataTemplate中。这应该让您有两个不同的命令可以点击NameCountry

<ListBox ItemsSource="{Binding CityList}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock x:name="Name" Text="{Binding Name }" >
                   <i:Interaction.Triggers>
                        <i:EventTrigger EventName="Tap">
                            <command:EventToCommand Command="{Binding NameSelectedCommand, Mode=OneWay}" CommandParameter="{Binding Path=SelectedItem, ElementName=CityList}" PassEventArgsToCommand="False"/>
                        </i:EventTrigger>
                   </i:Interaction.Triggers>
                </TextBlock>
                <TextBlock x:name="Country" Text="{Binding  Country}" >
                   <i:Interaction.Triggers>
                        <i:EventTrigger EventName="Tap">
                            <command:EventToCommand Command="{Binding CountrySelectedCommand, Mode=OneWay}" CommandParameter="{Binding Path=SelectedItem, ElementName=CityList}" PassEventArgsToCommand="False"/>
                        </i:EventTrigger>
                   </i:Interaction.Triggers>
                </TextBlock>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>