我在运行时生成它时将行为(Blend SDK中的行为)附加到UIElement。我还有两个按钮来触发分离()和附加() - 基本上是为了启用或禁用该行为。
问题是:在 Detach()行为之后, Attach()无法将行为还原到依赖项对象,然后保持无行为:< / p>
// 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...
为什么行为没有重新附加?是否有解决方案或解决方案来打开或关闭行为?
答案 0 :(得分: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>