我正在尝试使用附加属性来触发UIElement
事件触发时的样式更改。
以下是案例场景:
用户看到TextBox
,然后聚焦然后取消聚焦。它在附加属性中的某处注意到此LostFocus
事件并设置一个属性(某处?)来表示它HadFocus
。
然后,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);
}
}
谁能指导我?