开发者

How to get multiple controls to fire same event/command in Silverlight / XAML?

I am using Mvvm-Light Commands to route events from my Views to my ViewModels. Works great.

But I think I can be more elegant. This is actually probably just a standard XAML question:

I want to change this (10 buttons all with Click="keypadButton_Click" for their event handler):

<Button  Name="button1" Content="1" Grid.Row="0" Grid.Column="0" Click="keypadButton_Click" />
<Button  Name="button2" Content="2" Grid.Row="0" Grid.Column="1" Click="keypadButton_Click"/>
<Button  Name="button3" Content="3" Grid.Row="0" Grid.Column="2" Click="keypadButton_Click"/>
<Button  Name="button4" Content="4" Grid.Row="1" Grid.Column="0" Click="keypadButton_Click"/>
<Button  Name="button5" Content="5" Grid.Row="1" Grid.Column="1" Click="keypadButton_Click"/>
<Button  Name="button6" Content="6" Grid.Row="1" Grid.Column="2" Click="keypadButton_Click"/>
<Button  Name="button7" Content="7" Grid.Row="2" Grid.Column="0" Click="keypadButton_Click"/>
<Button  Name="button8" Content="8" Grid.Row="2" Grid.Column="1" Click="keypadButton_Click"/>
<Button  Name="button9" Content="9" Grid.Row="2" Grid.Column="2" Click="keypadButton_Click"/>
<Button  Name="button0" Content="0" Grid.Row="3" Grid.Column="1" Click="keypadButton_Click"/>

To 10 of these:

<Button  x:Name="button1" Content="1" Grid.Row="0" Grid.Column="0">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName=开发者_如何学JAVA"Click">
            <Command:EventToCommand 
               Command="{Binding KeyPadButtonCommand}"
               CommandParameter="{Binding ElementName=button1, Path=Content }"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

But I don't want that much XAML. I would think there would be a way to "macroize" the Trigger so it would look something like this:

<Button  Name="button1" Content="1" Grid.Row="0" Grid.Column="0" 
         Click="{Binding _SendTheEventHere_}" />

Where "{Binding _SendTheEventHere_}" should be replaced with some magic incantation that I am clueless about, but I know some wizard here on stackoverflow knows :-).

Make sense?


I'm not sure if I understand you correctly, but you can use RelayCommand in MVVM Light Toolkit here is a sample code

Generally RelayCommand are implementation of ICommand interface that you can use


I have just run a test using the following XAML and it seems to work successfully :-

Your Button XAML :-

<Button Name="MyConfirmButton" 
        Content="Confirm" 
        Grid.Column="1" 
        Style="{StaticResource ButtonStyle}"
        i:Interaction.Triggers="{StaticResource PerformConfirm}">
</Button>

Your Resource XAML :-

<UserControl.Resources>
   <i:EventTrigger x:Key="PerformConfirm" EventName="Click">
      <cmd:EventToCommand Command="{Binding Path=PerformConfirm}" />
   </i:EventTrigger>
</UserControl.Resources>

Hope this helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜