Wpf DataGrid SelectionChanged在滚动时触发事件
我正在尝试实现一种行为,以允许我的Wpf DataGrid SelectionChanged在滚动时触发事件,wpf,datagrid,Wpf,Datagrid,我正在尝试实现一种行为,以允许我的DataGrid移动到DataGrid底部新添加的一行。我有一些按钮,可以在添加新行时从ItemsSource添加/删除项目,并通过编程设置SelectedCensusReportMapping 我找到了这个解决方案(),它将新添加的行显示在DataGrid中。我遇到的问题是,当我尝试滚动数据网格时,当前选定的行始终保持在视图中,并且我无法滚动到其他行,这会将选定的行推离屏幕 下面是myDataGrid的实现: <DataGrid Name="D
DataGrid
移动到DataGrid
底部新添加的一行。我有一些按钮,可以在添加新行时从ItemsSource
添加/删除项目,并通过编程设置SelectedCensusReportMapping
我找到了这个解决方案(),它将新添加的行显示在DataGrid
中。我遇到的问题是,当我尝试滚动数据网格时,当前选定的行始终保持在视图中,并且我无法滚动到其他行,这会将选定的行推离屏幕
下面是myDataGrid的实现:
<DataGrid Name="DataGrid_CensusReportMapping"
ItemsSource="{Binding Model.CensusReportMappings, UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding SelectedCensusReportMapping, UpdateSourceTrigger=PropertyChanged}"
AutoGenerateColumns="False"
CanUserAddRows="False"
CanUserDeleteRows="False">
<i:Interaction.Behaviors>
<h:ScrollIntoDataGridBehavior />
</i:Interaction.Behaviors>
</DataGrid>
我使用下面的代码
void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (sender is DataGrid)
{
DataGrid grid = (sender as DataGrid);
if (grid.SelectedItem != null)
{
grid.Dispatcher.BeginInvoke(
(Action)(() =>
{
if (grid.SelectedItem != null)
{
grid.ScrollIntoView(grid.SelectedItem);
grid.UpdateLayout();
}
}));
}
}
}
它工作得很好,但最近我发现当我在datagrid中使用DataGridComboxColumn时,一些特定的窗口出现了您的问题
奇怪的是,在某些页面是罚款的,但在某些窗口是不罚款的
当datagridcomboboxcolumn具有itemsource和i滚动时,我发现是selectionchanged事件触发器
我不知道如何修复,所以我使用datagridtemplatecolumn并将combobox放在scroll/maximize窗口上的模板中。。。等等。这看起来像一个datagrid bug。
根本原因:datagrid中一列或多列的内容负责触发selectionchanged事件,即使未触及任何行。在我的例子中,这是由于向datagrid公开了一个Enum属性。我必须将Enum属性更改为int属性,以避免selectionchanged甚至在scroll上触发
人们在使用时报告了相同的行为:
-列中的组合框
-列中的listview
-等等,我最近在一个带有ComboBoxColumn的DataGrid上遇到了同样的问题。我通过检查SelectionChangedChangedEventArgs
的OriginalSource
属性,设法解决了这个问题
当SelectionChanged事件由ComboBox列引起时,OriginalSource属性是ComboBox控件。当SelectionChanged事件由数据网格引起时(例如,通过设置SelectedItem),原始源是数据网格本身
这是为我工作的代码
private void DataGridSelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid dg = sender as DataGrid;
if (e.OriginalSource == dg && dg.SelectedItem != null)
dg.ScrollIntoView(dg.SelectedItem);
}
private void DataGridSelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid dg = sender as DataGrid;
if (e.OriginalSource == dg && dg.SelectedItem != null)
dg.ScrollIntoView(dg.SelectedItem);
}