依赖属性不依赖于交互行为

时间:2016-05-10 14:16:06

标签: c# wpf xaml dependency-properties

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

修改后的班级RubberBandBehavior

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>

1 个答案:

答案 0 :(得分:2)

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