[英]How to select a TextBox inside a datagrid cell when the cell is selected in WPF?
我有一個數據網格,其中第一列的單元格覆蓋有文本框。 如果我用鼠標選擇“單元格”沒問題,因為我只能單擊“文本框”,但是當我用鍵盤導航時,我可以導航到下面的單元格。 我嘗試設置單元格樣式,但TextBox繼承了設置。 當選擇下面的單元格時,是否可以將焦點移到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>
您需要創建“行為”以強制文本框模糊化( myTextBox.Focus()
)。 此行為應在TextBox實例上分配,並綁定到IsFoucsed
的屬性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();
}
}
}));
}
那應該為您工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.