2017-08-10 64 views
1

這是我的第一次嘗試使用擴展帶有依賴項屬性的文本框,基於我在網上找到的一個示例。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> 

結果如下: enter image description here

運行它會導致此行崩潰:

<custom:CustTextBox Text="TESTING"></custom:CustTextBox> 

回答

4

你需要改變:

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)以避免任何魔法字符串。

編輯:我也注意到你是如何通過0PropertyMetadata。這與您聲明該屬性的類型不同。您已將其宣佈爲string,但傳遞的是int。通過這個PropertyMetadata("0")或更改屬性類型爲int

+0

我做了改變,但我仍然有同樣的問題。關於你的最後一條評論:什麼是魔術字符串,你是在暗示「SecurityId」被nameof(SecurityId)替換? –

+0

是的,這就是我所建議的,因爲如果您重命名'SecurityId'屬性,但忘記更改依賴項屬性中的''SecurityId''',您將遇到問題並且很難找出原因。 –

+0

好的,但即使使用nameof(SecurityId)作爲註冊的第一個參數,問題仍然存在。 –