[英]wpf attached property do not working
我只是想將參數傳遞給控件。 但是它引發了錯誤“輸入字符串的格式不正確”。 為什么?* *
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();
}
}
您從未聽過更改。
您可以使用構造函數調用時SecurityId
的值來構造DataViewModel
。 這是默認的""
。 然后,您通過XAML將值更改為"abc"
。 但是這種變化並沒有傳遞到任何地方。 它發生了,沒有人在乎。 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
}
順便說一下,它不是附屬財產。 這是一個普通的依賴項屬性。
這是因為,您試圖將“ 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.