具有依赖性 属性 崩溃的 wpf 自定义文本框

wpf custom textbox with a depedency property crash

这是我第一次尝试使用扩展具有依赖性的文本框 属性,基于我在网上找到的示例。

我的解决方案包含 2 个项目:一个 wpf 应用程序和一个 class 库。

这是我的 class 图书馆:

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));
 }
}

这是我尝试使用 CustTextBox 的 wpf 应用程序 xaml(应用程序本身没什么特别的,只是使用 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.