wpf自定义文本框与依赖属性崩溃
问题描述:
这是我的第一次尝试使用扩展带有依赖项属性的文本框,基于我在网上找到的一个示例。wpf自定义文本框与依赖属性崩溃
我的解决方案由2个项目组成:一个wpf应用程序和一个类库。
这里是我的类库:
namespace CustomTextBox
{
public class CustTextBox : TextBox
{
public string SecurityId
{
get { return (string)GetValue(SecurityIdProperty); }
set { SetValue(SecurityIdProperty, value); }
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SecurityIdProperty =
DependencyProperty.Register("MyProperty", typeof(string), typeof(CustTextBox), new PropertyMetadata(0));
}
}
这里的WPF应用程序的XAML,我尝试使用CustTextBox(应用程序本身是没有什么特别的,只是用caliburn.micro.start)
<Window x:Class="TestWPFApplication.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:custom="clr-namespace:CustomTextBox;assembly=CustomTextBox">
<Grid>
<custom:CustTextBox Text="TESTING"></custom:CustTextBox>
</Grid>
</Window>
运行它会导致此行崩溃:
<custom:CustTextBox Text="TESTING"></custom:CustTextBox>
答
你需要改变:
public static readonly DependencyProperty SecurityIdProperty =
DependencyProperty.Register("MyProperty", typeof(string), typeof(CustTextBox), new PropertyMetadata(0));
要:
public static readonly DependencyProperty SecurityIdProperty =
DependencyProperty.Register("SecurityId", typeof(string), typeof(CustTextBox), new PropertyMetadata("0"));
其实你应该能够使用nameof(SecurityId)
以避免任何魔法字符串。
编辑:我也注意到你是如何通过0
到PropertyMetadata
。这与您声明该属性的类型不同。您已将其宣布为string
,但传递的是int
。通过这个PropertyMetadata("0")
或更改属性类型为int
。
我做了改变,但我仍然有同样的问题。关于你的最后一条评论:什么是魔术字符串,你是在暗示“SecurityId”被nameof(SecurityId)替换? –
是的,这就是我所建议的,因为如果您重命名'SecurityId'属性,但忘记更改依赖项属性中的''SecurityId''',您将遇到问题并且很难找出原因。 –
好的,但即使使用nameof(SecurityId)作为注册的第一个参数,问题仍然存在。 –