依赖项 属性 无法处理交互行为

Dependency property not working on a interaction behavior

我正在尝试将依赖项 属性 IsActive 添加到我在 CodeProject 上找到的 RubberBandBehavior,以便我可以从我的 ViewModel 激活和停用它。下面的代码没有给出任何编译错误并运行,但是当我检查带有注释 \ this line is always 'false'.

的行时,该值似乎设置不正确

修改后classRubberBandBehavior:

public class RubberBandBehavior : Behavior<ListBox>
{

    public static readonly DependencyProperty IsActiveProperty =
        DependencyProperty.Register("IsActive", typeof(bool), typeof(RubberBandBehavior),
        new PropertyMetadata(IsActiveProperty_Changed));

    private static void IsActiveProperty_Changed(DependencyObject sender,
        DependencyPropertyChangedEventArgs args)
    {
        // This gets called _after_ OnAttached!
    }

    public bool IsActive
    {
        get { return (bool)GetValue(IsActiveProperty); }
        set { SetValue(IsActiveProperty, value); }
    }

    protected override void OnAttached()
    {
        AssociatedObject.Loaded += new System.Windows.RoutedEventHandler(AssociatedObject_Loaded);
        base.OnAttached();
    }

    void AssociatedObject_Loaded(object sender, System.Windows.RoutedEventArgs e)
    {
        bool a = IsActive; // this line is always 'false'

        RubberBandAdorner band = new RubberBandAdorner(AssociatedObject);
        AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(AssociatedObject);
        adornerLayer.Add(band);
    }

    protected override void OnDetaching()
    {
        AssociatedObject.Loaded -= new System.Windows.RoutedEventHandler(AssociatedObject_Loaded);
        base.OnDetaching();
    }
}

在我的 XAML 我有这个:

        <i:Interaction.Behaviors>
            <behavior:RubberBandBehavior IsActive="True"/>
        </i:Interaction.Behaviors>

然后我的计划是像这样绑定到我的 ViewModel,但首先我需要解决上面的问题:

        <i:Interaction.Behaviors>
            <behavior:RubberBandBehavior IsActive="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.IsEditable}"/>
        </i:Interaction.Behaviors>

您不会在 AssociatedObject.Loaded 事件中获得此值。您需要在代码示例中使用 IsActiveProperty_Changed 处理程序来获取此 属性

的正确值