2015-08-18 127 views
2

我只是想將參數傳遞給控件。但它引發錯誤「輸入字符串格式不正確」。爲什麼* *wpf附屬屬性不起作用

的XAML

<Views:SomeView SecurityId="abc"></Views:SomeView> 

型號:

class Data 
{ 
    public string Case { get; set; } 
    public Data(int _input) 
    { 
     if (_input==1) 
     { 
      Case = "First"; 
     } 
     else 
     { 
      Case = "Second"; 
     } 
    } 
} 

視圖模型:

class DataViewModel 
{ 
    public string GetData 
    { 
     get 
     { 
      return D.Case; 
     } 

     set 
     { 
      D.Case = value; 
     } 
    } 

    public Data D; 
    public DataViewModel(string i) 
    { 
     D = new Data(Convert.ToInt16(i)); 
    } 

} 

主窗口

public partial class SomeView : UserControl 
{ 
    public string SecurityId 
    { 
     get 
     { 
      return (string)GetValue(SecurityIdProperty); 
     } 
     set { SetValue(SecurityIdProperty, value); } 
    } 
    public static readonly DependencyProperty 
     SecurityIdProperty = 
     DependencyProperty.Register("SecurityId", 
     typeof(string), typeof(SomeView), 
     new PropertyMetadata("")); 

    public SomeView() 
    { 
     DataContext = new DataViewModel(SecurityId); 
     InitializeComponent(); 
    } 
} 
+0

''abc「'不能用'Convert.ToInt16(i)'分析。 – Sinatr

+0

我知道,它的錯誤。但是DataViewModel中的i值的主要問題在於「」。例如,當我改變// D =新數據(Convert.ToInt16(i));與Debug.WriteLine(i);.它正在打印「」,而不是「abc」 – A191919

回答

3

你從來不聽更改。

您構造DataViewModel的值爲SecurityId在構造函數調用時的值。這是默認的""。然後通過XAML將值更改爲​​。但是這種變化並不是隨處可見的。它發生了,沒人關心。您的DataViewModel的構建已完成。

你想聽聽變化嗎?我不能說。您需要爲您的依賴項屬性註冊一個更改處理程序。

在你PropertyMetaData你可以傳遞一個改變的事件處理程序,第二個參數,例如靜態方法:

public static readonly DependencyProperty 
    SecurityIdProperty = 
    DependencyProperty.Register("SecurityId", 
    typeof(string), typeof(SomeView), 
    new PropertyMetadata("", new PropertyChangedCallback(MyValueChanged))); 

然後,您可以有能力處理變化的方法:

private static void MyValueChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs) 
{ 
    // react on changes here 
} 

這不是順便說一下附屬的財產。這是一個正常的依賴屬性。

+0

你能展示如何實現? – A191919

+0

@ A191919添加了一條關於實現它的線。 – nvoigt

0

這是因爲,您試圖將「abc」解析爲整數,但您沒有處理由ConvertTo.Int16()方法引起的異常。
寫DataViewModel構造一樣,

public DataViewModel(string i) 
    { 
     int value = 0; 
     int.TryParse(i, out value); // TryParse handles the exception itself. 
     D = new Data(value); 
    } 
+0

沒有任何變化。依賴屬性的工作是不正確的,它總是有價值的「」 – A191919

+0

@ A191919如果你問爲什麼你得到'輸入字符串格式不正確',那麼這個答案解釋了原因,因此是正確的答案。但如果你問爲什麼'SecurityId'總是''「',你應該編輯你的問題。 –