首页 > 解决方案 > WPF Datagrid 在 MVVM 架构中获取单元格值

问题描述

如何从 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 页面中,我添加了 textblock 以测试哪些文本绑定到 datagrid currentCell。当我单击鼠标右键时,它会正确显示 int 值。但是在我的 GetValue(object data) 函数控制台中,第一次右键单击返回 null,第二次返回 int 值,但控制台中的值始终与文本块值不同,我必须在同一个单元格上单击两次才能获得正确的单元格位置。那是完全错误的。如何解决?

另一个问题:如何从我绑定的 currentCell 中获得真正的价值?

我做了什么?2步:

在 xaml 中,我将 datagrid currentCell 绑定到 VM 属性CurrentCell="{Binding Cell}" ,我得到的值没问题,但它仍然只返回 DataGridCellInfo 对象。我试图投射到用户对象和各种东西,但我未能获得单元格的价值。有人可以提供从数据网格中获取单元格值的良好做法吗?

标签: wpfmvvmdatagridcell

解决方案


数据网格绑定到一组用户,因此每个用户由一行表示,而不是一个单元格。这就是为什么CurrentCell返回一个DataGridCellInfo

如果您想要用户,请绑定到CurrentItem

在 XAML 中:

<DataGrid 
    ItemsSource="{Binding Users}"
    CurrentItem="{Binding SelectedUser}"... 

在视图模型中:

private user selectedUser;
public user SelectedUser
{
    get => selectedUser;
    set
    {
        var u = value as user;
        selectedUser = u;
    }
 }

推荐阅读