2012-05-22 71 views
9

我試圖使用附加屬性來觸發事件發生時UIElement上的樣式更改。附加屬性來更新事件的樣式觸發器

這裏的情況:

的用戶將看到一個TextBox,重點然後unfocuses它。在某個附屬房產中,它注意到這個事件並設置了一個屬性(某處?)來表示它。

TextBox上的樣式知道它應該根據此HadFocus屬性以不同的樣式進行自定義。

以下是我想象中的標記看...

<TextBox Behaviors:UIElementBehaviors.ObserveFocus="True"> 
<TextBox.Style> 
    <Style TargetType="TextBox"> 
     <Style.Triggers> 
      <Trigger Property="Behaviors:UIElementBehaviors.HadFocus" Value="True"> 
       <Setter Property="Background" Value="Pink"/> 
      </Trigger> 
     </Style.Triggers> 
    </Style> 
</TextBox.Style> 

我已經試過附加屬性的幾個組合得到這個工作,我的最新嘗試拋出一個XamlParseException說明「觸發器上的屬性不能爲空。」

public class UIElementBehaviors 
{ 
    public static readonly DependencyProperty ObserveFocusProperty = 
     DependencyProperty.RegisterAttached("ObserveFocus", 
              typeof (bool), 
              typeof (UIElementBehaviors), 
              new UIPropertyMetadata(false, OnObserveFocusChanged)); 
    public static bool GetObserveFocus(DependencyObject obj) 
    { 
     return (bool) obj.GetValue(ObserveFocusProperty); 
    } 
    public static void SetObserveFocus(DependencyObject obj, bool value) 
    { 
     obj.SetValue(ObserveFocusProperty, value); 
    } 

    private static void OnObserveFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     var element = d as UIElement; 
     if (element == null) return; 

     element.LostFocus += OnElementLostFocus; 
    } 
    static void OnElementLostFocus(object sender, RoutedEventArgs e) 
    { 
     var element = sender as UIElement; 
     if (element == null) return; 

     SetHadFocus(sender as DependencyObject, true); 

     element.LostFocus -= OnElementLostFocus; 
    } 

    private static readonly DependencyPropertyKey HadFocusPropertyKey = 
     DependencyProperty.RegisterAttachedReadOnly("HadFocusKey", 
                typeof(bool), 
                typeof(UIElementBehaviors), 
                new FrameworkPropertyMetadata(false)); 

    public static readonly DependencyProperty HadFocusProperty = HadFocusPropertyKey.DependencyProperty; 
    public static bool GetHadFocus(DependencyObject obj) 
    { 
     return (bool)obj.GetValue(HadFocusProperty); 
    } 

    private static void SetHadFocus(DependencyObject obj, bool value) 
    { 
     obj.SetValue(HadFocusPropertyKey, value); 
    } 
} 

任何人都可以指導我嗎?

回答

5

註冊readonly依賴項屬性並不意味着將Key添加到屬性名稱。僅僅通過

DependencyProperty.RegisterAttachedReadOnly("HadFocus", ...); 

因爲HadFocus是屬性的名稱替換

DependencyProperty.RegisterAttachedReadOnly("HadFocusKey", ...); 

+0

這就是解決辦法,感謝您的幫助:o) – mortware

相關問題