我有以下代码:
<StackPanel Orientation="Vertical">
<GridView
Background="Azure"
x:Name="ContactList"
ItemsSource="{Binding Path=Users}"
SelectedItem="{Binding SelectedUser, Mode=TwoWay}">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="SelectionChanged">
<core:InvokeCommandAction
Command="{Binding MyCommandOnTheViewModel, Mode=OneWay}"/>
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
<GridView.ItemTemplate>
<DataTemplate>
<Border Width="300" Height="Auto" BorderThickness="1">
<StackPanel Orientation="Vertical">
<TextBlock HorizontalAlignment="Left">
<Run FontWeight="Bold" Text="{Binding Name}" />
<Run Text="{Binding Age}" />
</TextBlock>
<StackPanel Orientation="Horizontal">
<Button Content="Button1" HorizontalAlignment="Left"></Button>
<Button Content="Button2" HorizontalAlignment="Right"></Button>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</StackPanel>
此时,当我单击列表中的项目时,命令:MyCommandOnTheViewModel
将被执行。如您所见,我还有一个包含两个按钮的StackPanel
。如何将两个单独的命令绑定到每个按钮?
我一直试图给我的按钮名称,以为我能以某种方式执行以下操作:
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="SelectionChanged" ELEMENTNAME="MyButtonsName">
<core:InvokeCommandAction
Command="{Binding MyCommandOnTheViewModel, Mode=OneWay}"/>
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
但似乎没有这样的工作。 任何提示赞赏!
这对我有用:
<Button Content="MyButton"
Command ="{Binding ElementName=ContactList,Path=DataContext.MyCommand}"></Button>
感谢您的帮助@Utsav
答案 0 :(得分:0)
您可以为每个按钮提供Command
属性。通过这种方式,您可以轻松地在viewmodel中将两个单独的命令与单击事件上的两个按钮绑定。
请参阅下面的代码。
<StackPanel Orientation="Vertical">
<GridView
Background="Azure"
x:Name="ContactList"
ItemsSource="{Binding Path=Users}"
SelectedItem="{Binding SelectedUser, Mode=TwoWay}">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="SelectionChanged">
<core:InvokeCommandAction
Command="{Binding MyCommandOnTheViewModel, Mode=OneWay}"/>
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
<GridView.ItemTemplate>
<DataTemplate>
<Border Width="300" Height="Auto" BorderThickness="1">
<StackPanel Orientation="Vertical">
<TextBlock HorizontalAlignment="Left">
<Run FontWeight="Bold" Text="{Binding Name}" />
<Run Text="{Binding Age}" />
</TextBlock>
<StackPanel Orientation="Horizontal">
<Button Content="Button1" HorizontalAlignment="Left" Command="{Binding CommandLeftBtn}"></Button>
<Button Content="Button2" HorizontalAlignment="Right" Command="{Binding CommandRightBtn}"></Button>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</StackPanel>