我正在尝试使用附加属性在事件触发时触发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);
}
}
有人能指导我吗?
答案 0 :(得分:5)
注册只读依赖项属性并不意味着将Key
添加到属性名称。只需替换
DependencyProperty.RegisterAttachedReadOnly("HadFocusKey", ...);
通过
DependencyProperty.RegisterAttachedReadOnly("HadFocus", ...);
因为HadFocus
是属性的名称。