[英]Binding to a Property of UserControl
我寫了一個包含很多東西的小部件,它包含一個屬性(DependencyProperty),該屬性正在UC類內部進行更新(基於在文本框中鍵入的輸入和來自按鈕單擊等的輸入。)其定義是:
public partial class UserControlClassName : UserControl, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public static readonly DependencyProperty ValueProperty = System.Windows.DependencyProperty.Register("Value", typeof(string), typeof(UserControlClassName), new PropertyMetadata(string.Empty, OnValueChanged));
public string Value
{
get { return (string)GetValue(ValueProperty); }
set
{
SetValue(ValueProperty, value);
NotifyPropertyChanged("Value");
}
}
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != null && e.NewValue != e.OldValue)
{
Console.Out.WriteLine("new value: " + e.NewValue);
}
}
...
...
lots of other code that updates the Value property..
...
...
}
我在某些窗口的XAML中實例化UC,如下所示:
<GeneralControls:UserControlClassName
x:Name="someRandomName"
Value="{Binding MyViewModel.MyBoundedValueField, StringFormat=N2, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource DebugBinding}}"
VerticalAlignment="Bottom" />
為了完成圖片,這是我用來“抓取”值的視圖模型的屬性:
public string MyBoundedValueField
{
get { return myBoundedValueField; }
set
{
if (myBoundedValueField!= value)
{
myBoundedValueField = value;
OnPropertyChanged("MyBoundedValueField");
}
}
}
我的問題是-用戶控件內的Value屬性確實得到了更新,但是我綁定到xaml(myBoundedValueField)中的外部屬性沒有獲得更新..與此綁定屬性綁定的某些東西不起作用-所以我附加了一個轉換器來調試它,並且轉換器沒有被調用,所以它肯定是錯誤的綁定設置。
(向任何幫助的人致謝!)
解決方案最終是添加Mode = TwoWay
<GeneralControls:UserControlClassName
x:Name="someRandomName"
Mode=TwoWay
Value="{Binding MyViewModel.MyBoundedValueField, StringFormat=N2, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource DebugBinding}}"
VerticalAlignment="Bottom" />
我不知道為什么沒有它,裝訂無法工作-我很想聽聽一個解釋,說明any1可以使這個主題有些陰影。
特別感謝@Clemens !!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.