我在WPF应用程序中使用了Border Control。我想改变设定焦点的背景。为此,编写了以下代码,但它无法正常工作。
Style _Style = new System.Windows.Style(typeof(Border));
Trigger _Trigger = new Trigger();
_Trigger.Property = Border.IsFocusedProperty;
_Trigger.Value = true;
_Trigger.Setters.Add(new Setter(Border.BackgroundProperty, Brushes.Green));
_Style.Triggers.Add(_Trigger);
Border1.Style = _Style;
答案 0 :(得分:1)
这适用于XAML定义的样式:
<Style x:Key="FocusBorder" TargetType="{x:Type Border}">
<Setter Property="Focusable" Value="True"/>
<Setter Property="Background" Value="Blue"/>
<Style.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="Background" Value="Green"/>
</Trigger>
</Style.Triggers>
</Style>
....
<Border x:Name="MyBorder" Width="100" Height="100" VerticalAlignment="Center" HorizontalAlignment="Center" Style="{DynamicResource FocusBorder}" SnapsToDevicePixels="True"/>
代码背后:
Window_Loaded(object sender, RoutedEventArgs e)
{
MyBorder.Focus();
}
默认情况下,边框不是Focusable
,因此您必须将Focusable
设置为true
。并且还要记住键盘焦点仅限于输入元素,其中边框不是一个。
答案 1 :(得分:1)
忽略你可以(并且几乎肯定应该)在XAML中执行此操作的事实,问题是双重的:
IsKeyboardFocusWithin
,而不仅仅是IsFocused
。