我在Caliburn微型项目中有一个简单的wpf数据网格。我正在使用 TestClass 的实例初始化行。如果用户选择此行标题之一,我想获取 TestClass 的实例。但是互联网上的所有值和所有示例都只能在单元格中显示文本。
那么如何从数据网格获取用于创建单元格的对象呢?
ShellViewModel.cs:
using System.Collections.Generic;
using System.Data;
using System.Windows.Controls;
using Caliburn.Micro;
namespace TestSelectionChanged.ViewModels
{
class ShellViewModel : Screen
{
private DataTable _profileColumnRows;
public DataTable ProfileColumnRows
{
get => _profileColumnRows;
set
{
if (Equals(value, _profileColumnRows)) return;
_profileColumnRows = value;
NotifyOfPropertyChange();
}
}
public ShellViewModel()
{
ProfileColumnRows = new DataTable("test");
ProfileColumnRows.Columns.Add("test1");
ProfileColumnRows.Columns.Add("test2");
// Here are the TestClass objects I want to get later
ProfileColumnRows.Rows.Add(new TestClass("testc","a","b"));
ProfileColumnRows.Rows.Add(new TestClass("testd", "c", "d"));
}
public void OnSelectionCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
var dataGrid = ((DataGrid) sender);
var column = dataGrid.SelectedCells[0].Column;
var columnIndex = dataGrid.SelectedCells[0].Column.DisplayIndex;
var rowIndex = dataGrid.Items.IndexOf(dataGrid.SelectedCells[0].Item);
}
}
class TestClass
{
public string name { get; set; }
public List<string> Items { get; set; }
public TestClass(string name, params string[] items)
{
this.name = name;
Items = new List<string>(items);
}
public override string ToString()
{
return name;
}
}
}
ShellView.xaml:
<UserControl x:Class="TestSelectionChanged.Views.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:cal="http://www.caliburnproject.org"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<StackPanel>
<DataGrid
ItemsSource="{Binding ProfileColumnRows}"
cal:Message.Attach="[Event SelectedCellsChanged] = [Action OnSelectionCellsChanged($source,$eventArgs)]"/>
</StackPanel>
</UserControl>
我想在第一个选定的单元格中获取对象,如果它是 TestClass 类型,我想访问其 Items 属性。这可能吗?
首先,不清楚为什么您尝试将 DataTable 与 TestClass 实例用作行。为此,您需要弄清楚如何将TestClass的每个属性转换为DataTable中的不同列。更好的方法是将数据网格直接绑定到List<TestClass>
。
例如
public ShellViewModel()
{
ProfileColumnRows.Add(new TestClass("testc", "a", "b"));
ProfileColumnRows.Add(new TestClass("testd", "c", "d"));
}
public List<TestClass> ProfileColumnRows {get;set;} = new List<TestClass>();
现在来谈谈访问选定项的问题,您可以使用SelectedItem
属性
<DataGrid
ItemsSource="{Binding ProfileColumnRows}" SelectedItem="{Binding SelectedItem}"
/>
并在视图中模型
public TestClass SelectedItem { get; set; }