我有一些间歇性工作的代码,我无法理解为什么(直到今天早上Windows自动安装了一些更新,但没有与.NET 4相关的工作 - 在我的项目中使用的版本)。
我的密码框......
<PasswordBox x:Name="TboxPassword" Grid.Row="1" Grid.Column="0"
controls:TextboxHelper.Watermark="Password ..."
controls:TextboxHelper.ClearTextButton="True"
Margin="10, 10, 0, 0">
<i:Interaction.Behaviors>
<misc:PasswordBoxBehavior Password="{Binding Path=Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"/>
</i:Interaction.Behaviors>
</PasswordBox>
我的行为:
public class PasswordBoxBehavior : Behavior<PasswordBox>
{
#region Fields
private readonly object _tryToExecuteActionSyncObject = new object();
private bool _isUpdating;
#endregion
#region Properties
public string Password
{
get { return (string)GetValue(PasswordProperty); }
set { SetValue(PasswordProperty, value); }
}
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.Register("Password", typeof(string), typeof(PasswordBoxBehavior),
new PropertyMetadata(string.Empty, OnPasswordPropertyChanged));
#endregion
#region Methods
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.PasswordChanged += OnAssociatedObjectPasswordChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.PasswordChanged -= OnAssociatedObjectPasswordChanged;
}
private void OnAssociatedObjectPasswordChanged(object sender, RoutedEventArgs e)
{
TryToExecuteAction(() => Password = AssociatedObject == null
? string.Empty
: AssociatedObject.Password);
}
private static void OnPasswordPropertyChanged
(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
PasswordBoxBehavior passwordBoxBehavior;
if (sender == null
|| (passwordBoxBehavior = sender as PasswordBoxBehavior) == null
|| passwordBoxBehavior.AssociatedObject == null)
{
return;
}
passwordBoxBehavior.TryToExecuteAction
(() => passwordBoxBehavior.AssociatedObject.Password =
(e.NewValue == null
? string.Empty
: (string) e.NewValue));
}
private void TryToExecuteAction(Action actionToExecute)
{
bool continueExecution;
lock (_tryToExecuteActionSyncObject)
{
continueExecution = _isUpdating == false;
_isUpdating = true;
}
if (continueExecution == false)
{
return;
}
try
{
if (actionToExecute != null)
{
actionToExecute();
}
}
finally
{
lock (_tryToExecuteActionSyncObject)
{
_isUpdating = false;
}
}
}
#endregion
}
我得到0(零)编译错误。运行应用程序时,90%的时间我收到运行时异常,说明:
{"Cannot add instance of type 'PasswordBoxBehavior' to a collection of type 'BehaviorCollection'. Only items of type 'T' are allowed."}
调试器在标签Interaction.Behaviors
处停止请记住,直到今天我才收到此错误。现在我收到它,即使我恢复了今天所做的一切。
请告知..:D
PS:我刚刚从行为内部注释掉了所有代码。还删除了密码绑定。仍然无法运作:(
PPS:如果我关闭Visual Studio(2012),删除我的bin文件夹,打开VS,打开项目,重建所有,应用程序 WORKS ,直到第一次更改代码。
答案 0 :(得分:1)
我知道这个问题很老了。但我会发布答案以防有人再次面对它。
我刚遇到同样的问题而且我找到了解决方案,我注意到您在代码中使用了行为。只需确保您正在引用正确版本的Blend SDK Windows.Interactivity
在我的情况下,问题是我在主WPF项目上仅为WPF 4.5安装了NugetPackage for Blend SDK,我忘了将它安装在使用行为的解决方案中的其他WPF项目上。
我通过在包含导致问题的代码的项目上安装相同的NugetPackage解决了这个问题。
希望这能帮到你!