[英]WPF DataGrid TargetType=“DataGridRow” not working for Event=“MouseDoubleClick”
[英]WPF DataGrid DataGridRow override ItemsPanel breaks tab order
我正在一個WPF項目中,該項目需要一個2D網格,該網格需要在窗口內擴展和收縮。 為此,我用UniformGrids替換了DataGrid中的ItemsPanels。 當我這樣做時,控件將正確展開和收縮。
不幸的是,由於某種原因,這破壞了DataGrid中的選項卡順序。 如果按Tab鍵,它將下拉一行,而不是跳到下一列。 當選項卡到達行尾時,它將轉到下一列的頂部並繼續向下。 左,右,上,下箭頭鍵均按預期工作,受影響的唯一功能是按Tab鍵順序。 如果刪除DataGridRow樣式,則制表符順序將自行更正,但行不會隨窗口擴展。
這個問題似乎並沒有孤立到UniformGrid上,因為StackPanel也會產生相同的選項卡症狀。
有誰知道我應該怎么尋找或尋找解決此選項卡問題的方法,或者可能是使網格根據需要擴展和收縮的另一種方法?
XAML示例:
<Window x:Class="SODatagridSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<UniformGrid IsItemsHost="True" Rows="1" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<Grid>
<DataGrid x:Name="datagrid" ItemsSource="{Binding Values}" SelectionMode="Extended" SelectionUnit="Cell" ColumnWidth="*" HeadersVisibility="None"
CanUserAddRows="False" CanUserDeleteRows="False">
<DataGrid.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="1"></UniformGrid>
</ItemsPanelTemplate>
</DataGrid.ItemsPanel>
</DataGrid>
</Grid>
</ScrollViewer>
后面的示例代碼:
using System.ComponentModel;
using System.Data;
using System.Windows;
namespace SODatagridSample
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
public DataTable Values
{
get { return _Values; }
set
{
_Values = value;
OnPropertyChanged(nameof(Values));
}
}
private DataTable _Values;
public MainWindow()
{
Values = new DataTable();
for (int i = 0; i < 15; i++)
Values.Columns.Add(i.ToString(), typeof(double));
for (int i = 0; i < 10; i++)
Values.Rows.Add(Values.NewRow());
for (int x = 0; x < 10; x++)
for (int y = 0; y < 15; y++)
Values.Rows[x][y] = x * 15 + y;
DataContext = this;
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
解決方法非常簡單。 反映出DataGridCellPanel之后,我注意到它具有以下靜態構造函數:
static DataGridCellsPanel()
{
KeyboardNavigation.TabNavigationProperty.OverrideMetadata(typeof(DataGridCellsPanel), new FrameworkPropertyMetadata((object)KeyboardNavigationMode.Local));
}
所需要做的就是擴展UniformGrid以添加該靜態構造函數,或者只是向DataGridRow樣式的UniformGrid中添加附加屬性KeyboardNavigation.TabNavigation =“ Local”:
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<UniformGrid KeyboardNavigation.TabNavigation="Local" IsItemsHost="True" Rows="1"/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.