如何访问Button的绑定值?

时间:2011-07-05 11:50:54

标签: c# wpf data-binding event-handling

我有以下XAML

<Window.Resources>
    <DataTemplate x:Key="SelectButtonColumnDataTemplate">
        <Button Content="Select" Command="{Binding SelectItemCommand}" Click="SelectButtonClick" />
    </DataTemplate>
</Window.Resources>

<Grid x:Name="LayoutRoot">
<ListView x:Name="listFeedSearch" HorizontalAlignment="Left" Width="542.5" RenderTransformOrigin="0.5,0.5" ItemsSource="{Binding SearchCollection}">
    <ListView.RenderTransform>
        <TransformGroup>
            <ScaleTransform/>
            <SkewTransform/>                
            <RotateTransform/>                
            <TranslateTransform/>            
            </TransformGroup>        
            </ListView.RenderTransform>        
    <ListView.View>            
        <GridView>                
            <GridViewColumn Width="150" Header="Feed Name" x:Name="listFeedSearchName" DisplayMemberBinding="{Binding FeedName}"  />                
            <GridViewColumn Width="280" Header="Feed Address" x:Name="listFeedSearchAddress" DisplayMemberBinding="{Binding FeedUrl}" />                
            <GridViewColumn Width="100" Header=" " CellTemplate="{StaticResource SelectButtonColumnDataTemplate}" />            
        </GridView>        
        </ListView.View>    
</ListView>     
</Grid>

添加以下事件处理程序:

private void SelectButtonClick(object sender, RoutedEventArgs e)
        {

        }

我想要做的是输出单个绑定值的行。

我将如何做到这一点,我知道这有点像:

var data = (sender as Button)...

由于

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要使用{Binding}Xaml: Binding to the current DataContext

参考:Understand WPF Binding CommandParameter="{Binding}"

答案 1 :(得分:1)

如果将按钮CommandParameter设置为(感谢Bolu):

"{Binding}"

然后以下代码将检索当前单击的对象并显示消息框。其中foo是用于填充gridview的类

 public class foo
 {
    string FeedName {get;set;}
    string FeedUrl {get;set;}
 }

 public void InitialiseListView(List<Foo> Items)
 {
    listFeedSearch.ItemsSource = Items;
 }

 private void SelectButtonClick(object sender, RoutedEventArgs e)
 {
    foo b = (foo)(sender as Button).CommandParameter;

    string s = string.format("Name: {0} URL: {1}",b.FeedName,b.FeedUrl);
    MessageBox.Show(s);
}