我有一个具有依赖项属性的用户控件,并且正在wpf窗口中使用此控件。当我从窗口视图模型更改为绑定到该依赖项属性的属性的值时,我希望该依赖项属性的回调方法将被调用,但不会发生任何事情。
MainWindow.xaml
<test:TestView Grid.Column="0" TestString="{Binding TestString, Mode=TwoWay}"></test:TestView>
MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainWindowViewModel();
}
MainWindowViewModel.cs
private string _testString;
public string TestString
{
get { return _testString; }
set
{
if (_testString!= value)
{
_testString= value;
OnPropertyChanged();
}
}
}
TestView.xaml.cs
public TestView()
{
InitializeComponent();
this.DataContext = new TestViewModel();
}
public static readonly DependencyProperty TestStringProperty =
DependencyProperty.Register("TestString", typeof(string), typeof(TestView), new PropertyMetadata(null, OnTestStringPropertyChanged));
public string TestString
{
get { return (string)GetValue(TestStringProperty); }
set
{
SetValue(TestStringProperty, value);
}
}
private static void OnTestStringPropertyChanged(DependencyObject source,
DependencyPropertyChangedEventArgs e)
{
TestView control = source as TestView;
string time = (string)e.NewValue;
// Put some update logic here...
((TestViewModel) control.DataContext).Merge();
}
BaseViewModel.cs(我在每个ViewModel中都进行了扩展)
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
我在这里做错了什么,或者为什么从未调用过我的回调?