【发布时间】:2016-02-09 02:08:01
【问题描述】:
我有一个带有 3 列的 WPF Datagrid 作为窗口的一部分。 ItemsSource 是从一组支付对象(grdPayments.ItemsSource = 付款)中设置的。当焦点在后面的代码中设置为网格时,我希望第一行中的第三个单元格获得焦点。
无论我使用以下哪种方法,都会选择并聚焦第二行而不是第一行。
这会将焦点设置到第二行的第三个单元格:
grdPayments.Focus();
grdPayments.CurrentCell = new DataGridCellInfo(grdPayments.Items[0],grdPayments.Columns[2]);
grdPayments.SelectedCells.Add(dataGridCellInfo);
cell.Focus();
grdPayments.BeginEdit();
这会将焦点设置到第二行:
grdPayments.Focus();
grdPayments.SelectedIndex = 0;
grdPayments.BeginEdit();
谁能告诉我发生了什么事? DataGrid XAML 如下。 my:NumberEntry 是一个自定义控件:
<DataGrid Name="grdPayments"
AutoGenerateColumns="False"
Background="#FF21B721"
ItemsSource="{Binding}"
SelectionUnit="Cell"
SelectionMode="Single"
Margin="5"
VirtualizingPanel.IsVirtualizing="False">
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Background" Value="#FF21B721"/>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Width="240"
Binding="{Binding Path=Description}"
Header="Description"
IsReadOnly="True"
TextBlock.TextAlignment="Center">
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="{StaticResource clBr}"/>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
<DataGridTemplateColumn Width="100" Header="Due">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Width="100" Text="{Binding Path=Due, Converter={StaticResource CurrencyPadder}, ConverterParameter=10}" Background="{StaticResource clBr}" Focusable="False"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Width="100" Header="Paid">
<DataGridTemplateColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="{StaticResource clBr}"/>
</Style>
</DataGridTemplateColumn.CellStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<my:NumberEntry Decimals="2"
LostFocus="NumberEditor_LostFocus"
PreviewKeyDown="NumberEditor_PreviewKeyDown"
MaxLength="10"
TextAlignment="Right"
Text="{Binding Path=Paid, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
【问题讨论】:
-
明确地说,我想在第一行中选择一个单元格,但只能选择整个第二行或第二行中的一个单元格。我已经尝试了我在网上找到的所有解决方案,但都无济于事。一定有办法!
-
好的。如果 SelectionUnit=Fullrow 和 SelectionMode=Extended,则选择第一行。我还需要做两件事:1)选择一个单元格。 2) 以编程方式将该单元格置于编辑模式。令人沮丧的是,DataGrid 的 WPF 版本让如此明显需要的功能变得如此困难。