【问题标题】:WPF Datagrid Get Cell Value in MVVM architectureWPF Datagrid 在 MVVM 架构中获取单元格值
【发布时间】: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 对象。我试图投射到用户对象和各种东西,但我未能获得单元格的价值。 有人可以提供从数据网格中获取单元格值的良好做法吗?

【问题讨论】:

    标签: wpf mvvm datagrid cell


    【解决方案1】:

    数据网格绑定到一组用户,因此每个用户由一行表示,而不是一个单元格。这就是为什么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;
        }
     }
    

    【讨论】:

    • 感谢您的重播。但是您是否测试过您的解决方案?它不起作用。
    • 我无法尝试您的确切代码,因为它不完整。我在我的测试程序中工作,但我注意到您使用的是SelectionUnit="Cell",需要将其删除才能使用 SelectedItem
    • 非常感谢。它有效:) 这是我的错误。
    • 但是如果我想获得一个单元格值,我已经实现了附加功能,例如: switch(cell.position): case 0 return name case 1 return depratament case 2 return another value?
    • 是的。但是 MVVM 的想法是 ViewModel 可以使用用户的属性,而不必考虑网格中的单元格。视图应该被视为只是一种可视化数据的方式,这与 Windows 窗体不同,后者需要一个复杂的可视对象来操作数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多