2

背景:我正在实现一个将行为附加到对象的系统*。它在代码中按预期工作,但在 XAML 中却不行。

*是的,我知道Microsoft.Expression.Interactivity.dll

简而言之,我希望能够做到这一点..

<Rectangle>
    <m:BehaviorExtensions.Behavior>
        <m:HoverBehavior />
    </m:BehaviorExtensions.Behavior>
</Rectangle>

..但似乎只能这样做:

<Window.Resources>
    <m:HoverBehavior x:Key="Hover" />
</Window.Resources>

<Rectangle m:BehaviorExtensions.Behavior="{DynamicResource Hover}" />

m:BehaviorExtensions当我尝试使用嵌套标签(如顶部的如意示例中)标记它时,[甚至]不会出现在 Intellisense 中。我在这里想念什么?

这是定义附加属性的代码:

public static class BehaviorExtensions
{
    public static readonly DependencyProperty BehaviorProperty = DependencyProperty.RegisterAttached("Behavior", typeof(IBehavior), typeof(BehaviorExtensions), new FrameworkPropertyMetadata(null, BehaviorChangedCallback));

    public static void SetBehavior(UIElement element, IBehavior behavior)
    {
        if (element == null) { throw new ArgumentNullException("element"); }
        element.SetValue(BehaviorProperty, behavior);
    }

    public static IBehavior GetBehavior(UIElement element)
    {
        if (element == null) { throw new ArgumentNullException("element"); }
        return (IBehavior)element.GetValue(BehaviorProperty);
    }

    private static void BehaviorChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        IBehavior behavior;
        if (e.OldValue != null)
        {
            behavior = (IBehavior)e.OldValue;
            behavior.DetachFrom((UIElement)d);
        }
        if (e.NewValue == null) return;
        behavior = (IBehavior)e.NewValue;
        behavior.AttachTo((UIElement)d);
    }
}

编辑 - 经验教训:

事实证明这很好用。需要与程序配合使用的是 Intellisense(字面意思)。当我完全忽略它并只输入我想要的内容时,事情就顺利进行了 - 即编译时没有打嗝。当谈到 XAML 时,对 Intellisense 的尊重显然是医生的命令。

4

0 回答 0