开发者

Event handler for dynamically created buttons in WPF form

Im trying to create a WPF Form with gridview which have a "button column", like this: http://rghost.ru/4832825.view

I'm creating "button column" by specifying DataTemplate for column.

And now I encountered a problem: I need to write buttons event handler, but I don't understand, how to determine which button was pressed in the column? How I can determine this without using Tag field of buttons?

This is my code. XAML:

<Window x:Class="ListViewSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="317" Width="603">

<Window.Resources>
    <DataTemplate x:Key="ButtonInColumn">
        <Button Content="Test" Height="20" Name="button1" Width="40"  Click="MenuItem_Click"/>
    </DataTemplate>

</Window.Resources>

<Grid>
    <ListView Margin="10,75,12,38" Name="ListView1">
        <ListView.View>
            <GridView AllowsColumnReorder="true" ColumnHeaderToolTip="Authors">
                <!-- Add GridView Columns -->
                <GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Path=Name}"/>
                <GridViewColumn Header=" Age" Width="60" CellTemplate="{StaticRe开发者_StackOverflow中文版source ButtonInColumn}" />
                <GridViewColumn Header=" Book" Width="250" DisplayMemberBinding="{Binding Path=Book}" />
                <GridViewColumn Header=" MVP" Width="50" DisplayMemberBinding="{Binding Path=Mvp}" />
                <GridViewColumn Header=" 123" Width="50" DisplayMemberBinding="{Binding Path=q123}" />
            </GridView>
        </ListView.View>
    </ListView>
</Grid>
</Window>

p.s. sorry for my bad English


In the event handler you have object Sender. This sender is the button, and you can do the following:

var btn = sender as Button;
var dataItem = btn.DataContext as <the original data item class>

This way u have a reference to the original data item, and can extrapolate anything from there..

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜