Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding one control to another's DataContext

I bind my wpf window to app layer class (WindowVM.cs) using DataContext in Window.xaml.cs constructor (DataContext = WindowVM). But, one control (btnAdd) I want to bind to Window.xaml.cs property. So in Window.xaml.cs constructor I add this.btnAdd.DataContext. This is Window.xaml.cs constructor and property to which I want bind Button btnAdd:

    public Window()
    {
        InitializeComponent();
        DataContext = WindowVM;
        this.btnAdd.DataContext = this;
    }

    public RelayCommand Add
    {
        get
        {
            return _add == null ? _add= new RelayCommand(AddPP, CanAddPP) : _add;
        }
        set
        {
            OnPropertyChanged("Add");
        }
    }

Xaml looks like this (class PP is WindowVM property):

<TextBox Name="txtName" Text="{Binding PP.Name, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Name="txtSurname" Text="{Binding PP.Surname, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" />
<Button Command="{Binding Add}" Content="Add" ... />

And - everything works, but console output this:

BindingExpression path error: 'Add' property not found on 'object' ''WindowVM'...

In next calls there isn't any console output error for property Add.

Now I am a little bit confused because of this error. Is this error because of first DataContext (to WindowVM), because there isn't property Add, but with line this.btnAdd.DataContext property Add is found and it's the reason that it works?

like image 556
davor Avatar asked Mar 16 '26 08:03

davor


1 Answers

Simply set the DataContext of the Button in the XAML using a RelativeSource:

<Button Command="{Binding Add}" Content="Add" DataContext="{Binding Add, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" />
like image 109
Rafael Costa Avatar answered Mar 17 '26 20:03

Rafael Costa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!