2012-05-22 11 views
9

イベントが発生したときに添付プロパティを使用してUIElementのスタイル変更をトリガーしようとしています。ここでイベントのスタイルトリガーを更新するための添付プロパティ

は、ケースのシナリオである:

ユーザーがTextBoxを見て、それをunfocusesその後、焦点を当てています。アタッチされたプロパティのどこかで、このLostFocusイベントに気付き、それをHadFocusと言うプロパティ(どこか?)を設定します。

このTextBoxのスタイルは、このHadFocusプロパティに基づいて異なるスタイルを設定する必要があることを認識しています。

は、ここで私は私の最新の試みがを述べXamlParseExceptionをスローし、この作業を取得するために添付プロパティのいくつかの組み合わせを試してみた

<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> 

...私は見てマークアップを想像する方法です"Triggerでプロパティをnullにすることはできません。"

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

読み取り専用依存プロパティを登録しても、プロパティ名にKeyを追加することを意味するものではありません。ただ、プロパティの名前です

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

HadFocus以降で

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

を交換してください。

+0

これは修正です、ご協力ありがとうございます:o) – mortware

関連する問題