Search code examples
c#wpfmvvmdata-binding

How to databind property from view model to custom user control in WPF?


I have a custom control that I created to test how binding works. It has a dependency property that I want to bind from another view and also I want it to update when binded property raises PropertyChanged using INotifyPropertyChanged:

public string BindLabelText
{
    get { return (string)GetValue(BindLabelTextProperty); }
    set { SetValue(BindLabelTextProperty, value); }
}

public static readonly DependencyProperty BindLabelTextProperty =
    DependencyProperty.Register("BindLabelText", typeof(string), typeof(BindingControl), 
    new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

In my control I bind dependency property like this:

<TextBlock 
    Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"
    Text="{Binding ElementName=TestControl, Path=BindLabelText,  FallbackValue=BindLabelText}" 
    FontSize="20"/>

And I use control like this:

<local:BindingControl BindLabelText="Static main window value" />
<local:BindingControl BindLabelText="{Binding HeaderLabel, FallbackValue=HeaderLabel}" />
<Button Content="Change MainWindow property" Command="{Binding ChangeMainTextCommand}"/>

TextBlock text value is set with a static value but it does not work when I try to bind it to a property. In both views I set DataContext to ViewModel in code behind:

this.DataContext = new BindingControlViewModel();

Edit: Added my code to github. Like I said in the comments I'm trying to bind property on MainWindowViewModel which is the DataContext for my parent View (MainWindow) to my User Control DP BindLabelText. User Control in addition to DP also has its own ViewModel. My goal is to have User Control that will update when bound property from MainWindowViewModel updates.


Solution

  • I managed to solve it by setting my control DataContext to grid like MyGrid.DataContext = new BindingControlViewModel(); instead of setting it on the control itself like this.DataContext = new BindingControlViewModel();.