I have the following classes:
MainWindow.xaml
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<local:MyControl Margin="8" MyProperty="{Binding MyPropertyParent}" />
</Grid>
MainWindowViewModel.cs
public class MainWindowViewModel : ObservableObject
{
public string MyPropertyParent
{
get
{
return _myProperty;
}
set
{
_myProperty = value;
this.OnPropertyChanged();
}
}
private string _myProperty;
public MainWindowViewModel()
{
MyPropertyParent = "IT WORKS!!!";
}
}
MyControl.xaml
<UserControl.DataContext>
<local:MyControlViewModel/>
</UserControl.DataContext>
<Border CornerRadius="4" Background="White" BorderThickness="1" BorderBrush="#FFB0AEAE">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<Border Grid.Row="0" Background="#FFC6C6FB">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Margin="4" FontSize="16" VerticalAlignment="Center" HorizontalAlignment="Left"
Text="{Binding MyPropertyHack}" />
</Grid>
</Border>
</Grid>
</Border>
MyControl.xaml.cs
public partial class MyControl : UserControl
{
public string MyProperty
{
get { return (string)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register(
nameof(MyProperty),
typeof(string),
typeof(MyControl),
new PropertyMetadata(null, MyPropertyPropertyChanged));
private static void MyPropertyPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
((MyControl)o)._viewModel.MyPropertyHack = (string)e.NewValue;
}
public MyControlViewModel _viewModel;
public MyControl()
{
InitializeComponent();
if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
return;
_viewModel = App.Provider.GetService<MyControlViewModel>();
this.DataContext = _viewModel;
}
}
MyControlViewModel.cs
public class MyControlViewModel : ObservableObject
{
private string _myPropertyHack;
public string MyPropertyHack
{
get
{
return _myPropertyHack;
}
set
{
if (_myPropertyHack != value)
{
_myPropertyHack = value;
this.OnPropertyChanged();
}
}
}
public MyControlViewModel()
{
}
}
I'm trying to get it so MainWindow.xaml can pass a property set in its view model through to the DependencyProperty of MyControl. However, when I run it the TextBlock's Text field is empty and so "IT WORKS!!!" is not being shown on the screen and my breakpoint in MyPropertyPropertyChanged is not being hit.
What am I doing wrong?