开发者

XAML arguments for Click event

I have the following XAML:

<Button Name="btnJeans" Click="btnJeans_Click" Padding="-1" >
    <StackPanel Orientation="Horizontal" Margin="0,0,0,17" Name="jeansItem">
        <!--Replace rectangle with image-->
        <Image Height="119" Width="82" 开发者_运维问答Source="{Binding Image}" Margin="12,0,9,0"/>
        <StackPanel Width="311">                                    
            <TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
            <TextBlock Text="{Binding Price}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
        </StackPanel>
    </StackPanel>
</Button>

However, btnJeans_Click needs to pass "{Binding Name}" as an argument.

How would I do this? I'm developing for Windows Phone 7.


An alternative on the pc is to get get the DataContext from the click event args e.g.

private void Button_Click(object sender, RoutedEventArgs e)
    {
      var record = ((Button)e.OriginalSource).DataContext;
      MessageBox.Show("Do something with " + record.ToString()); 
    }

this might be applicable to the phone as well?


I think you need to use a command instead of a button click event to do this so you can do:

<Button Name="btnJeans" Command="{Binding Path=ButtonClickCommand}" CommandParameter="{Binding Name}">
    ...
</Button>

You'll then need to expose ButtonClickCommand as a ICommand object.

How to do this will depend on the structure of the rest of your application. E.g. Using MVVM pattern etc.


XAML allows for you to set the BindingContext of a button.

See the example below that refers to the Id property of the object which will be passed to the click handler.

    <Button Name="btnJeans" Click="btnJeans_Click" Padding="-1" BindingContext="{Binding Id}">
<StackPanel Orientation="Horizontal" Margin="0,0,0,17" Name="jeansItem">
    <!--Replace rectangle with image-->
    <Image Height="119" Width="82" Source="{Binding Image}" Margin="12,0,9,0"/>
    <StackPanel Width="311">                                    
        <TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
        <TextBlock Text="{Binding Price}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
    </StackPanel>
</StackPanel>

You can then access the property using the sender's BindingContext object. In the example you can refer to id property within the handler.

    private void btnJeans_Clicked(object sender, EventArgs e)
    {
        var button = sender as Button;
        var id = button.BindingContext;

    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜