![](/img/trans.png)
[英]Update of a Dependency Property when variable or field on which it depends on changes
[英]Update field when property changes
這可能是一個基本問題,因為我是WPF的新手。
我有一個包含文本框和按鈕的UserControl(此問題的代碼已簡化):
<UserControl x:Name="this">
<TextBox Text="{Binding ElementName=this, Path=MyProperty.Value}"/>
<Button x:Name="MyButton" Click="Button_Click"/>
</UserControl>
在后面的代碼中,我已將“ MyProperty”注冊為DependencyProperty:
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(MyProperty), typeof(MyPropertyNumeric), new UIPropertyMetadata(null));
“ MyProperty”是由我定義的類,實現INotifyPropertyChanged。 “ MyProperty.Value”是對象類型。
單擊該按鈕時,我在后面的代碼中更改了MyProperty.Value。 我想讓TextBox自動顯示新值。 我希望上面的方法會起作用,因為我已經實現了INotifyPropertyChanged-但這沒有。任何人都知道該怎么做嗎?
更新屬性時,您是否使用屬性名稱調用OnPropertyChanged事件?
例如,
public class MyProperty : INotifyPropertyChanged {
private string _value;
public string Value { get { return _value; } set { _value = value; OnPropertyChanged("Value"); } }
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name) {
PropertyChangedEventHandler handler = PropertyChanged;
if(handler != null) {
handler(this, new PropertyChangedEventArgs(name));
}
}
}
確保使用您要更新的屬性的名稱觸發PropertyChanged事件,這一點很重要。
嘗試添加到Binding Mode =“ OneWay”,我不確定到底該怎么做
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.