2013-04-26 40 views
-1

我在WPF應用程序中採用了邊界控制。我想改變設置焦點的背景。爲此,編寫了以下代碼,但它不起作用。如何更改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

這就是XAML的用途,你知道的。 – 2013-04-26 15:04:58

回答

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,所以你必須設置Focusabletrue 。並且請記住鍵盤焦點僅限於輸入元素,其中邊界不是一個。

+0

謝謝你的建議。你的建議是有效的,但必須用IsFocused替換一個屬性IsKeyboardFocusWithin。因爲邊界內有一些內容。 – 2013-04-26 15:29:58

1

忽略了一個事實,你可以(而且幾乎可以肯定應該)在XAML這樣做,問題是雙重的:

  1. 邊框是不是默認可聚焦。
  2. 您可能想要IsKeyboardFocusWithin,而不僅僅是IsFocused
+0

謝謝你的建議。你的建議是有效的,但也必須設置另一個屬性Focusable = true – 2013-04-26 15:28:39

相關問題