通过Button从WPF GridViewColumn获取内容

时间:2015-02-24 05:27:09

标签: wpf wpf-controls

我在ListView中的GridView中有一个Button。单击该按钮时,我想从该按钮的网格视图的相应行中获取文本。任何人都可以帮我解决这个问题吗?

我的XAML是:

<ListView Name="resultList" ItemsSource="{Binding}" DockPanel.Dock="Top">
 <ListView.View>
  <GridView AllowsColumnReorder="true" ColumnHeaderToolTip="Test Results Summary">
   <GridViewColumn DisplayMemberBinding= "{Binding Date}" Header="Date" Width="Auto"/>
    <GridViewColumn DisplayMemberBinding= "{Binding Status}" Header="Status" Width="Auto"/>
     <GridViewColumn Header="" Width="Auto">
      <GridViewColumn.CellTemplate>
       <DataTemplate >
        <Button x:Name="btnRemoveTest" Click="_viewResult" Content="View" Height="20" Width="100"/>
       </DataTemplate>
      </GridViewColumn.CellTemplate>
     </GridViewColumn>
    </GridView>
   </ListView.View>
  </ListView>

我可以在这做什么:

private void _viewResult(object sender, RoutedEventArgs e)
{
}

1 个答案:

答案 0 :(得分:1)

使用DataContext的{​​{1}},如下所示。请注意,在此示例代码中,我使用的是Customer。

Button

以下是完整的工作代码。

<强> MainWindow.xaml.cs

private void _viewResult(object sender, RoutedEventArgs e)
{
    Button button = sender as Button;
    Customer cust = button.DataContext as Customer;

    string sDate = cust.Date;
    string sStatus = cust.Status;
}

<强> MainWindow.xaml

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ListViewButtonClick
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            resultList.ItemsSource = new Customers();
        }
        private void _viewResult(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            Customer cust = button.DataContext as Customer;
            string sDate = cust.Date;
            string sStatus = cust.Status;
        }
    }
    public class Customer
    {
        public String Date { get; set; }
        public String Status { get; set; }

        public Customer(String Date, String Status)
        {
            this.Date = Date;
            this.Status = Status;
        }
    }
    public class Customers : ObservableCollection<Customer>
    {
        public Customers()
        {
            Add(new Customer("11/23/2015", "in progress"));
            Add(new Customer("11/24/2015", "Done"));
            Add(new Customer("11/22/2015", "Not yet done")); 
        }
    }
}