【问题标题】:Am I using the wrong datagrid?我使用了错误的数据网格吗?
【发布时间】:2019-09-06 21:07:47
【问题描述】:

我在 WPF 中有一个程序,我在 Datagrid 中加载了一堆数据。

数据网格 xaml:

<Window x:Class="test.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:test"
        mc:Ignorable="d"
        Title="Window1" Height="450" Width="800">
    <Grid>
        <DataGrid x:Name="dataGrid" Margin="10" Loaded="DataGrid_Loaded" ClipToBounds="True" AutoGenerateColumns="True" SelectionChanged="DataGrid_SelectionChanged_2" >
            <DataGrid.Columns>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

然后我在 Datagrid 中添加一个 Combobox 列

代码:

DataTable table = new DataTable();

DataGridComboBoxColumn dgvCmb = new DataGridComboBoxColumn();

dgvCmb.ItemsSource = new List<string>
{
    "Ghanashyam",
    "Jignesh",
    "Ishver",
    "Anand"
};
dataGrid.Columns.Add(dgvCmb);

这些值是临时用于测试的,稍后会更改。

这个想法是用户根据该行中的其他数据在 Combobox 中选择某些内容(我当前的测试集是 810 行长)。

我遇到的问题是,每当我在组合框中选择某些内容并更改行时,所选数据都会从前一行中删除。

很自然,我认为我需要自己处理这个问题。在互联网上搜索了一下后,我发现了这个:

https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.datagridview.rowleave?view=netframework-4.8

但是当我尝试实现这一点时,我发现我的 Datagrid 无法识别该事件。

我检查了一下,显然有两个命名空间包含一个 Datagrid 对象:

system.windows.forms.datagrid

system.windows.controls.datagrid

我是不是用错了?因为在 Visual Studio 的工具箱中,我只看到一个 Datagrid。

如果可以更好地处理这种情况,我们将不胜感激。

【问题讨论】:

  • System.Windows.Controls 是 WPF,System.Windows.Forms 是 WinForms。两种不同的框架。

标签: c# wpf


【解决方案1】:

您应该使用SelectedItemBinding 将选定的值存储在DataTable 的列中的ComboBox 中:

DataTable table = new DataTable();
table.Columns.Add(new DataColumn("SelectedValue"));

DataGridComboBoxColumn dgvCmb = new DataGridComboBoxColumn();
dgvCmb.SelectedItemBinding = new Binding("SelectedValue");
dgvCmb.ItemsSource = new List<string>
{
    "Ghanashyam",
    "Jignesh",
    "Ishver",
    "Anand"
};
dataGrid.Columns.Add(dgvCmb);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    相关资源
    最近更新 更多