【发布时间】:2011-03-19 02:10:00
【问题描述】:
我已经实现了一些自定义行为和触发器,并通过 XAML 添加了它们。它们在运行时工作正常,但会阻止 Cider 设计器视图在设计时加载,并且可能也会在 Blend 中引起问题,尽管我尚未确认。
以下是我为其中一种行为实现的概述;希望有人能指出我所缺少的。
行为看起来像这样;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Interactivity;
namespace MiX.Core.UI.Silverlight
{
public class UpdateOnTextChangedBehavior : Behavior<TextBox>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.TextChanged += OnAssociatedObjectTextChanged;
}
void OnAssociatedObjectTextChanged(object sender, TextChangedEventArgs e)
{
BindingExpression binding = this.AssociatedObject.GetBindingExpression(TextBox.TextProperty);
if (binding != null)
{
binding.UpdateSource();
}
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.TextChanged -= OnAssociatedObjectTextChanged;
}
}
}
XAML 中的实现如下所示;
<TextBox x:Name="Username" Text="{Binding Username,Mode=TwoWay}" BorderThickness="1" Style="{StaticResource TextBoxStyleGeneral}" Foreground="#FF333333" FontSize="10" BorderBrush="{x:Null}" Grid.Column="1" d:LayoutOverrides="GridBox" Margin="2,0" Grid.ColumnSpan="2" Background="{x:Null}" VerticalAlignment="Center" Grid.Row="1">
<i:Interaction.Behaviors>
<mixcore:UpdateOnTextChangedBehavior/>
</i:Interaction.Behaviors>
</TextBox>
在 XAML 编辑器中,<mixcore:UpdateOnPasswordChangedBehavior/> 元素以波浪形突出显示并报告错误“UpdateOnTextChangedBehavior”类型的值无法添加到“BehaviorCollection”类型的集合或字典中。尝试在设计视图中查看时,设计器加载失败,说明文档包含在加载设计器之前必须修复的错误。
【问题讨论】:
-
开始一个新项目并复制您的示例代码在 VS2010 中似乎可以正常工作(对我来说),没有设计器或 Blend 问题。您是否在代码隐藏中使用 TextBox 或 Behavior 做其他事情?
-
丹,看来你是对的。在真正的应用程序中,除了此行为之外还有两个操作,我看到其中一个是调用一个使用反射来设置依赖项属性值的方法。也许这就是阻止它在设计时工作的原因。
标签: silverlight xaml triggers behavior