如何从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>
VM:
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页面中,我添加了textblock来测试将哪些文本绑定到datagrid currentCell。当我单击鼠标右键时,它将正确显示int值。但是在我的Getvalue(对象数据)函数控制台中,第一次单击右键返回null,从第二次返回int值,但是控制台中的值始终与textblock值不同,我必须在同一单元格上单击两次以获取正确的单元格位置。那是完全错误的。该怎么解决?
另一个问题:如何从我绑定的currentCell中获得实际价值?
我做了什么? 2个步骤:
在xaml中,我将datagrid currentCell绑定到VM属性CurrentCell="{Binding Cell}"
我知道可以,但是仍然只返回datagridcellInfo对象。我试图强制转换为Users对象和其他各种东西,但是我无法获得单元的价值。
有人可以提供良好的做法来从Datagrid获取单元值吗?