I know this question is similar with Accessing items in ObservableCollection bound to WPF DataGrid
But the answers in this question doesn't helped me.
I've made a Class (DataItem.cs) where my ObservableCollection is. And another class (SelectableViewModel.cs) where the Properties for the Columns are.
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:
"MyProject.SelectableViewModel".
This is the way how I want to access to the 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).
But I don't know to solve this problem because I am not much familar with MVVM (rest of code is code-behind)
You need to cast the item to a SelectableViewModel
:
var selected = dataGrid.SelectedItems[0] as SelectableViewModel;
if (selected != null)
MessageBox.Show(selected.ColumnName);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.