【问题标题】:WPF Datagrid single click row to open new PageWPF Datagrid 单击行打开新页面
【发布时间】:2014-12-05 18:40:18
【问题描述】:

我在这里的第一篇文章!编码新手!...

我在页面的框架中有一个 WPF 数据网格。我想单击(最好单击)一行并使用存储在其中一列中的 ID 值导航到(打开)一个新页面。

使用 MouseDoubleClick 有时我可以双击行来打开一个页面。但有时它会抛出: “在 program.exe 中发生了“System.NullReferenceException”类型的未处理异常 附加信息:对象引用未设置为对象的实例。”

在线(完整方法见下方代码):

string ID = ((DataRowView)PersonDataGrid.SelectedItem).Row["PersonID"].ToString();

XAML:

<DataGrid x:Name="PersonDataGrid" AutoGenerateColumns="False" 
     SelectionMode="Single" SelectionUnit ="FullRow"      
     MouseDoubleClick="PersonDataGrid_CellClicked"  >
  <DataGrid.Columns>
      <DataGridTextColumn Binding="{Binding Path=PersonID}" 
          ClipboardContentBinding="{x:Null}" Header="ID"  />
  </DataGrid.Columns>
  <DataGrid.CellStyle>
      <Style TargetType="DataGridCell" BasedOn="{StaticResource myDataGridCellStyle}">
           <EventSetter Event="DataGridCell.MouseLeftButtonDown" Handler="PersonDataGrid_CellClicked"/>
      </Style>
   </DataGrid.CellStyle>
</DataGrid>

代码背后:

private void PersonDataGrid_CellClicked(object sender, MouseButtonEventArgs e)

    {
        string ID = ((DataRowView)PersonDataGrid.SelectedItem).Row["PersonID"].ToString();

        SelectedPersonID = Int32.Parse(ID);

        this.NavigationService.Navigate(new PersonProfile());
    }

有没有更好的方法来打开 PersonProfile 页面?有没有一种简单的方法可以通过单击一行来打开页面?

谢谢。

【问题讨论】:

  • 我删除了 XAML 中的 MouseDoubleClick="PersonDataGrid_CellClicked" 并将其替换为 DataGridCell.Selected="PersonDataGrid_CellClicked" 我现在可以单击打开页面。但是,发送者对象是 DataGridItems.Count,现在程序在 this.NavigationService.Navigate(new PersonProfile()); 上抛出错误
  • 使用 Joseph 的示例来实现此功能。感谢两位海报。

标签: c# wpf xaml datagrid click


【解决方案1】:

更好的方法是定义一个 Person 集合,定义 DataGrid ItemSource 和一个 Person 类型的属性,其中包含 DataGrid 中的选定项:

 <DataGrid x:Name="PersonDataGrid" AutoGenerateColumns="False" 
            SelectionMode="Single" SelectionUnit ="FullRow"       
            MouseRightButtonUp="PersonDataGrid_CellClicked" 
              ItemsSource="{Binding Persons}" 
              SelectedItem="{Binding SelectedPerson}">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=PersonId}" Header="Id"  />
            <DataGridTextColumn Binding="{Binding Path=PersonName}" Header="Name"  />
        </DataGrid.Columns>
    </DataGrid>

并且SelectedPerson 和Persons 在此页面后面的代码中定义如下:

 public partial class Page1 : Page,INotifyPropertyChanged
{
    private ObservableCollection<Person> _persons ;
    public ObservableCollection<Person> Persons
    {
        get
        {
            return _persons;
        }

        set
        {
            if (_persons == value)
            {
                return;
            }

            _persons = value;
             OnPropertyChanged();
        }
    }

    private Person _selectedPerson ;
    public Person SelectedPerson
    {
        get
        {
            return _selectedPerson;
        }

        set
        {
            if (_selectedPerson == value)
            {
                return;
            }

            _selectedPerson = value;
            OnPropertyChanged();
        }
    }
    public Page1()
    {
        InitializeComponent();
    }

    public event PropertyChangedEventHandler PropertyChanged;
    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}
public class Person
{
   public int PersonId { get; set; }
   public string PersonName { get; set; }
}

INotifyPropertyChanged 用于通知 UI 属性中的任何更改。 您可以使用SelectedPerson 属性或将其传递到新页面,例如在DataGrid 中收到MouseRightButtonUp 事件时:

    private void PersonDataGrid_CellClicked(object sender, MouseButtonEventArgs e)
    {
        if (SelectedPerson == null)
            return;
        this.NavigationService.Navigate(new PersonProfile(SelectedPerson));
    }

您可以更改 PersonProfile 页面以在其构造函数中接收 Person。

【讨论】:

  • 我目前正在使用由 SQL 查询填充的 DataSet 填充 DataGrid。那么我应该使用查询来填充 Person 类吗?
  • 是的,使用查询结果填充Persons Collection
  • 谢谢。这确实给出了单击结果。在您的示例中,我将 MouseRightButtonUp 更改为 MouseLeftButtonUp 以使用单击左键。现在尝试学习 MVVM!。
【解决方案2】:

您遇到的异常是因为 SelectedItem 有时为空。为确保您获得所需的值,请使用 sender 对象并将其转换为正确的类型。至于更好的方法,我会研究 MVVM 模式。这将涉及将 SelectedItem 绑定到对象。这可能有点多,因为您是新手,但这是我推荐的。

【讨论】:

  • 这是我不理解的部分内容。每行都有一个 PersonID 条目,并且有时只会出现错误。其他时候它工作正常。您能否详细说明建议的绑定?谢谢。
  • 我投了sender,发现错误发生时sender是datagrid的一个Item count。我在 XAML 中删除了 MouseDoubleClick="PersonDataGrid_CellClicked" 并且从那以后没有出现错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-30
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 2012-11-08
  • 1970-01-01
  • 2015-05-24
相关资源
最近更新 更多