1

当我在运行时生成它时,我将行为(Blend SDK 中的行为)附加到 UIElement。我还有两个按钮来触发Detach()Attach() - 基本上是启用或禁用该行为。

问题是:在我Detach()行为之后,Attach()未能将行为恢复到依赖对象,然后保持无行为:

// Declare the dependency object and behavior at class scope 
MyControl c = new MyControl();
MyBehavior b = new MyBehavior();

// Function that generate UI Controls with behavior attached
b.Attach(c);

// Function that detach behavior from dependency object
b.Detach();

// Function that re-attach behavior to the same object after it has been detached
b.Attach(c); // <-- Do not see the behavior...

为什么行为没有重新附加?是否有解决方案或解决方法来打开或关闭行为?

4

1 回答 1

1

看来问题是特定于您的行为逻辑的。在以下测试中,行为重新附加没有问题:

public class ColorBehavior : Behavior<Border>
{
    public Brush OriginalBrush { get; set; }

    protected override void OnAttached()
    {
        base.OnAttached();

        this.OriginalBrush = this.AssociatedObject.Background;
        this.AssociatedObject.Background = Brushes.CadetBlue;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        this.AssociatedObject.Background = this.OriginalBrush;
    }
}

public partial class MainWindow : Window
{
    private ColorBehavior behavior = new ColorBehavior();
    private bool isAttached;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (!this.isAttached)
        {
            this.behavior.Attach(this.Border);
            this.isAttached = true;
        }
        else
        {
            this.behavior.Detach();
            this.isAttached = false;
        }
    }
}

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow"
    Width="525"
    Height="350">
<Grid>
    <Border x:Name="Border" Background="Red" />
    <Button Width="50"
            Height="20"
            Click="Button_Click"
            Content="Hey" />
</Grid>

于 2012-11-14T16:36:01.797 回答