如何在WPF中选择单元格时选择DataGrid单元格内的TextBox?
问题描述:
我有一个datagrid,其中第一列的单元格覆盖了文本框。如果我用鼠标选择“单元格”没有问题,因为我只能点击文本框,但是当用键盘导航时,我可以导航到下面的单元格。我尝试设置单元格样式,但TextBox继承了设置。当选中底下的单元格时,是否有办法将焦点移动到文本框?如何在WPF中选择单元格时选择DataGrid单元格内的TextBox?
<DataGrid x:Name="buildDataGrid"
ItemsSource="{Binding BuildData}"
AutoGenerateColumns="False"
CanUserReorderColumns="False"
CanUserSortColumns="False"
CanUserResizeRows="False"
SelectionUnit="CellOrRowHeader"
CanUserAddRows="False"
CanUserDeleteRows="False"
KeyboardNavigation.TabNavigation="None"
Margin="0,0,10,0" IsReadOnly="True">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell" >
<Style.Setters>
<Setter Property="IsEnabled" Value="True"/>
<Setter Property="IsHitTestVisible" Value="False" />
</Style.Setters>
</Style>
</DataGrid.CellStyle>
<DataGrid.Columns>
<DataGridTemplateColumn Header="Serial Number"
MinWidth="200"
Width="*"
x:Name="componentSerialNumberDataGridTemplate">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding SerialNumber, UpdateSourceTrigger=PropertyChanged}"
x:Name="snoTextBox"
BorderThickness="0"
Focusable="True"
GotFocus="snoTextBox_GotFocus">
<TextBox.InputBindings>
<KeyBinding Command="{Binding SerialNumberEnterCommand}"
CommandParameter="{Binding Path=Text, ElementName=snoTextBox}"
Key="Return"/>
</TextBox.InputBindings>
</TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
答
您需要创建行为,迫使文本框foucsing(myTextBox.Focus()
)。 应在TextBox实例上分配此行为并绑定到DataCell的属性IsFoucsed
的实例。 类似的东西:
<TextBox Text="{Binding SerialNumber, UpdateSourceTrigger=PropertyChanged}"
x:Name="snoTextBox"
BorderThickness="0"
Focusable="True"
local:Behaviour.ForceFoucusBoolean="{Binding IsFocused, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridCell}}}"
GotFocus="snoTextBox_GotFocus">
<TextBox.InputBindings>
<KeyBinding Command="{Binding SerialNumberEnterCommand}"
CommandParameter="{Binding Path=Text, ElementName=snoTextBox}"
Key="Return"/>
</TextBox.InputBindings>
</TextBox>
你的行为是类似的东西:
class Behaviour
{
public static bool GetForceFoucusBoolean(DependencyObject obj)
{
return (bool)obj.GetValue(ForceFoucusBooleanProperty);
}
public static void SetForceFoucusBoolean(DependencyObject obj, bool value)
{
obj.SetValue(ForceFoucusBooleanProperty, value);
}
// Using a DependencyProperty as the backing store for ForceFoucusBoolean. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ForceFoucusBooleanProperty =
DependencyProperty.RegisterAttached("ForceFoucusBoolean", typeof(bool), typeof(Behaviour), new PropertyMetadata(null,
(o, e) =>
{
TextBox tb = o as TextBox;
if (tb != null)
{
bool foucs = Convert.ToBoolean(e.NewValue);
if (selctAll)
{
tb.Foucs();
}
else
{
tb.Unfocus();
}
}
}));
}
这应该为你工作。
谢谢@B先生,我试过了。不幸的是,它抱怨说,“默认值类型与属性类型'ForceFoucusBoolean''不匹配。 – Steven