[英]Accesing items in ObservableCollection bound to WPF DataGrid
I know this question is similar with Accessing items in ObservableCollection bound to WPF DataGrid 我知道这个问题类似于绑定到WPF DataGrid的ObservableCollection中的访问项
But the answers in this question doesn't helped me. 但这个问题的答案对我没有帮助。
I've made a Class (DataItem.cs) where my ObservableCollection is. 我创建了一个Class(DataItem.cs),我的ObservableCollection就在这里。 And another class (SelectableViewModel.cs) where the Properties for the Columns are.
另一个类(SelectableViewModel.cs),其中列的属性是。
public class DataItem : INotifyPropertyChanged
{
public ObservableCollection<SelectableViewModel> FirmCustomerItems { get; set; } = new ObservableCollection<SelectableViewModel>();
}
public class SelectableViewModel : INotifyPropertyChanged
{
private string _columnName;
public string ColumnName
{
get { return _columnName; }
set
{
if (_columnName== value) return;
_columnName= value;
OnPropertyChanged();
}
}
}
If I no want to access to the SelectedItem/Value/Items[0] I will get the following result: 如果我不想访问SelectedItem / Value / Items [0],我将得到以下结果:
"MyProject.SelectableViewModel". “MyProject.SelectableViewModel”。
This is the way how I want to access to the SelectedItem: 这是我想要访问SelectedItem的方式:
DataGrid dataGrid = sender as DataGrid;
switch (dataGrid.Name)
{
case "FirmCustomerTableDataGrid":
//var selected = dataGrid.SelectedValue; // my First try
//var selected = dataGrid.SelectedItem; // my Second try
var selected = dataGrid.SelectedItems[0] // my Third try
MessageBox.Show(selected.ToString());
break;
}
I the answers of the linked question at the top of my question is not working because I have a class for the column properties (SelectableViewModel). 我在问题顶部的链接问题的答案是行不通的,因为我有一个列属性类(SelectableViewModel)。
But I don't know to solve this problem because I am not much familar with MVVM (rest of code is code-behind) 但我不知道要解决这个问题,因为我对MVVM并不熟悉(其余的代码是代码隐藏)
You need to cast the item to a SelectableViewModel
: 您需要将项目转换为
SelectableViewModel
:
var selected = dataGrid.SelectedItems[0] as SelectableViewModel;
if (selected != null)
MessageBox.Show(selected.ColumnName);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.