Search code examples
c#wpfmvvm

WPF dependencyproperty must be used


Suppose I have MainWindow.xaml, and inside of it I have instance of UserControl1.xaml. Inside UserControl1.xaml I have TextBlock. Now suppose I have MainWIndowViewModel, can I bind the UserControl1 textblock's Text the MainWindowViewModel's property directly? or should I must use dependency property?


Solution

  • Assuming that UserControl1 is defined separately from MainWindow, so it can be reused elsewhere ...

    There is no straightforward way to directly bind the TextBox within UserControl1 to the MainWindow's ViewModel.

    Instead, you should add a Text property to UserControl1

    public string UC1Text
    {
        get=> (string)GetValue(UC1TextProperty); 
        set => SetValue(UC1TextProperty, value); 
    }
    
    public static readonly DependencyProperty UC1TextProperty =
        DependencyProperty.Register(nameof(UC1Text), typeof(string), typeof(UserControl1), new FrameworkPropertyMetadata(null)
                {
                    BindsTwoWayByDefault = true,
                    DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                });
    }
    

    and then bind its TextBox control to this new property using relative source binding

    <TextBox Text={Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl1}}, Path=UC1Text}
    

    Within MainWindow, you can now bind the UC1Text property of the UserControl1 instance to the appropriate property of the ViewModel.

    <MainWindow ...>
        <UserControl1 UC1Text={Binding VMText}