【发布时间】:2020-03-09 08:13:24
【问题描述】:
如何从 Datagrid 中获取选定的单元格值?
我查看了哪些信息? 标题为“WPF 获取单元格值 MVVM”的所有信息。
我做了什么? 1 步:
<Page x:Class="PDB.UsersView"
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:local="clr-namespace:PDB"
xmlns:PDB ="clr-namespace:PDBapi;assembly=PDBapi"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="UsersView"
>
<Page.DataContext>
<PDB:UsersViewModel/>
</Page.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!--Page Header info content-->
<Grid Grid.Row="0">
<TextBlock Text="{Binding ElementName=myGrd, Path=CurrentCell.Column.DisplayIndex}"/>
</Grid>
<!--Datagrid content-->
<DataGrid x:Name="myGrd"
SelectionMode="Single"
SelectionUnit="Cell"
IsReadOnly="True"
Grid.Row="1"
ItemsSource="{Binding Users}"
AutoGenerateColumns="True"
CanUserAddRows="False">
<DataGrid.InputBindings>
<MouseBinding MouseAction="RightClick"
Command="{Binding CellClickCommand}"
CommandParameter="{Binding ElementName=myGrd, Path=CurrentCell}" />
</DataGrid.InputBindings>
</DataGrid>
</Grid>
</Page>
虚拟机:
public UsersViewModel()
{
UserList = new ObservableCollection<User>();
GetUsers();
Users = CollectionViewSource.GetDefaultView(UserList);
CellClickCommand = new RelayParamCommand((data) => GetValue(data));
}
public void GetUsers()
{
User user = new User();
// Users = await user.GetUsers();
UserList.Add(new User
{
Name = "Marius",
Departament = "some",
Tabelis = 5
});
UserList.Add(
new User
{
Name = "Darius",
Departament = "unknown",
Tabelis = 20
});
}
private void GetValue(object data)
{
var some = (DataGridCellInfo)data;
//Returns only number
Console.WriteLine(some.Column?.DisplayIndex.ToString());
}
}
但是通过这种方法,我遇到了两个问题: 在 xaml 页面中,我添加了用于测试哪些文本绑定到 datagrid currentCell 的文本块。当我单击鼠标右键时,它会正确显示 int 值。但是在我的 GetValue(object data) 函数控制台中,第一次右键单击返回 null,第二次返回 int 值,但控制台中的值始终与文本块值不同,我必须在同一个单元格上单击两次才能获得正确的单元格位置。那是完全错误的。如何解决?
另一个问题:如何从我绑定的 currentCell 中获取实际值?
我做了什么? 2 步:
在 xaml 中,我将 datagrid currentCell 绑定到 VM 属性 CurrentCell="{Binding Cell}"
我得到的值没问题,但它仍然只返回 DataGridCellInfo 对象。我试图投射到用户对象和各种东西,但我未能获得单元格的价值。
有人可以提供从数据网格中获取单元格值的良好做法吗?
【问题讨论】: