添加新行时,WPF 的数据网格不会更新选定项



在 WPF 中使用 DataGrid 时,当直接从 UI 上的 DataGrid 添加新行时,SelectedItems 属性的大小总是在增长 - 即使在 UI 上始终选择单行进行编辑。

如何克服这个问题?为什么 SelectedItems 属性不反映 UI 上所选项目的实际数量?

我的代码:

SampleWindow.xaml

<Window x:Class="ALMClient.Controls.SampleWindow"
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:ALMClient.Controls"
mc:Ignorable="d" 
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0.9*"/>
<RowDefinition Height="0.1*"/>
</Grid.RowDefinitions>
<TabControl Name="tabControl" Grid.Row="0">
<TabItem Header="Test">
<DataGrid Name="dataGrid" VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch" CanUserAddRows="True" CanUserDeleteRows="True" AutoGenerateColumns="True" 
ItemsSource="{Binding GeneralTasks}" SelectionMode="Single" SelectionChanged="dataGrid_SelectionChanged" SelectionUnit="FullRow">
</DataGrid>
</TabItem>
</TabControl>
<TextBox Name="selectionBox" Grid.Row="1">
</TextBox>
</Grid>

SampleWindow.xaml.cs

using System.Windows;
namespace ALMClient.Controls
{
public partial class SampleWindow : Window
{
public SampleWindow()
{
InitializeComponent();
}        
private void dataGrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
this.selectionBox.Text = this.dataGrid.SelectedItems.Count.ToString();
}
}
}

您已将选择模式设置为单个

ItemsSource="{Binding GeneralTasks}" **SelectionMode="Single"** 

这意味着所选项目有点学术性。 您应该使用 SelectedItem 属性。

由于您正在绑定您的 itemssource,因此您没有使用 mvvm 方法并将 selecteditem 绑定到视图模型中的属性似乎很奇怪。 然后,您将代码放入该绑定属性的 setter 中,并在调用该属性时执行操作,而不是使用 selectionchange 事件。 喜欢这个: https://social.technet.microsoft.com/wiki/contents/articles/30564.wpf-uneventful-mvvm.aspx#Select_From_List_IndexChanged

我用来测试的东西是我有很多不同的风格和东西来演示和探索问题。它充满了垃圾和注释掉的位。

重要的位是数据网格和处理程序。 我有

<TabControl Name="tabControl" Grid.Row="0">
<TabItem Header="Test">
<DataGrid ItemsSource="{Binding Items}" 
RowHeight="30"
x:Name="dg"
Height="300" 
SelectionUnit="FullRow"
AutoGenerateColumns="true"
Sorting="dg_Sorting"
HeadersVisibility="All"
SelectionMode="Extended"
CanUserDeleteRows="true"
CanUserAddRows="True"
AlternationCount="2000"
AutoGeneratingColumn="dg_AutoGeneratingColumn_1"
SelectionChanged="dg_SelectionChanged"
>

我尝试使用单一和扩展的选择模式,绑定到可观察集合和数据表的视图。 它总是有效。

我的处理程序。

private void dg_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
this.countSelected.Text = dg.SelectedItems.Count.ToString();
}

这是压缩解决方案: https://1drv.ms/u/s!AmPvL3r385QhgooXOPWbZYGwuScJMQ

最新更新