Я нашел много статей по этому вопросу, но ни одна из них не работает. У меня есть 3 DataTemplateColumns, два с текстовыми полями и один с кнопкой переключения. Табуляция сначала переходит к ячейке, затем к содержимому. Я попробовал МНОГИЕ предложения с других сайтов и свои собственные изобретения, но безуспешно. Я могу заставить его работать в первой строке, и когда я добавляю другую, но добавляю по 2 за раз, и она перестает работать. Я ненавижу. Шаблон данных. Колонны. Вот класс, который я использую в настоящее время, используя свойство зависимости.
public class FocusAttacher
{
public static readonly DependencyProperty FocusProperty =
DependencyProperty.RegisterAttached("Focus",
typeof(bool),
typeof(FocusAttacher),
new PropertyMetadata(false, FocusChanged));
public static bool GetFocus(DependencyObject d)
{
return (bool)d.GetValue(FocusProperty);
}
public static void SetFocus(DependencyObject d, bool value)
{
d.SetValue(FocusProperty, value);
}
public static void FocusChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if ((bool)e.NewValue)
{
((UIElement)sender).Focus();
}
}
<DataGridTemplateColumn Header="Some Value"
MinWidth="30"
Width=".02*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding SomeBinding,
ValidatesOnDataErrors=True,
UpdateSourceTrigger=PropertyChanged}"
IsReadOnly="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type DataGrid}},
Path=DataContext.IsReadOnly}"
Style="{StaticResource SomeStyle}"
customControls:FocusAttacher.Focus="True"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
И как ни странно, это работает только для текстовых полей, а не для переключателя в моем третьем столбце. АРХ!!!!!
Редактировать: Вот DataTemplate для кнопки. Он настроен как настраиваемый элемент управления строго для стиля и триггера. Это кнопка с шаблоном управления, содержащим границу и презентатор контента.
<DataTemplate>
<customControls:MetroButton cal:Message.Attach="[Event Click] = [Action RemoveGroup($dataContext)]"
Width="15"
Height="15"
IsTabStop="False"
Focusable="False"
MouseOverBackground="LightGray">
<Button.Visibility>
<MultiBinding Converter="{StaticResource BoolsToVisibilityAndConverter}">
<Binding Path="IsReadOnly"
Converter="{StaticResource BooleanInverterConverter}"
RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}"/>
<Binding Path="IsDeletable"/>
</MultiBinding>
</Button.Visibility>
<TextBlock Text="-"
Focusable="False"
Margin="0 -6 0 0" />
</customControls:MetroButton>
</DataTemplate>
РЕДАКТИРОВАТЬ: Добавление пользовательского элемента управления кнопки.
<Button x:Class="Beacon.FlexCare.UI.CustomControls.MetroButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:customControls="clr-namespace:Beacon.FlexCare.UI.CustomControls"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="300"
MouseEnter="MetroButtonDefinition_MouseEnter"
MouseLeave="MetroButtonDefinition_MouseLeave"
customControls:FocusAttacher.Focus="True"
x:Name="MetroButtonDefinition">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="IsTabStop"
Value="False" />
<Setter Property="Focusable"
Value="False" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="rectangle"
BorderThickness="1.3"
Background="{TemplateBinding Background}"
BorderBrush="White"
Padding="{TemplateBinding Padding}">
<Border.Style>
<Style TargetType="{x:Type Border}">
<Setter Property="Focusable"
Value="False" />
</Style>
</Border.Style>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
RecognizesAccessKey="True"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
OpacityMask="White">
</ContentPresenter>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed"
Value="True">
<Setter Property="Background"
Value="#005285" />
</Trigger>
<Trigger Property="IsEnabled"
Value="False">
<Setter Property="Foreground"
Value="Gray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Foreground"
Value="White" />
<Setter Property="Background"
Value="Transparent" />
</Style>
</Button.Style>
Пожалуйста, помогите мне, прежде чем я застрелюсь. Спасибо