I have a user control with a dependency property and i am using this control in a wpf window. When i change from the window view model the value of a property that is put as binding to that dependency property, i expect the callback method for that dependency property to be invoked, but nothing happens.
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 (I extend it in every ViewModel)
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
What did i do wrong here or why my callback is never invoked?