2

My goal is to bind an element property in XAML to a property of the code behind class, while the DataContext still is a ViewModel.

The reason is, that I have some only UI-cosmetic properties in XAML which are not controlled by the ViewModel but by the code behind.

So essentially I search something like that:

<Element 
    Attribute = "{Binding ThatOneCodeBehind.WhateverProperty}"
    OtherAttribute1 = "{Binding StillDataContextSomething}" 
    OtherAttribute2 = "{Binding StillDataContextSomething}"
/>

What is the correct binding Syntax for Attribute="{Binding ThatOneCodeBehind:WhateverProperty}"?

ASh
  • 34,632
  • 9
  • 60
  • 82
user1470240
  • 580
  • 3
  • 19
  • 1
    Is 'ThatOneCodeBehind.WhateverProperty' a DependencyProperty of the main control that contains your 'Element' control? – Lupu Silviu Jun 29 '18 at 07:03
  • Give that element a name and you have access to it from Code. eg: ` – Nawed Nabi Zada Jun 29 '18 at 07:05
  • 2
    Assuming the "code behind" you are referring to is that of a Window, make sure WhateverProperty is a public property in the window class, and bind like `{Binding WhateverProperty, RelativeSource={RelativeSource AncestorType=Window}}`. – Clemens Jun 29 '18 at 07:18

1 Answers1

5

Your code behind is in some UIElement, let say Window. So give your element with code behind name and do bind to it. Of course property CodeBehindProperty should be defined there.

<Window x:Name="_this">
    <TextBox Text="{Binding CodeBehindProperty, ElementName=_this}"/>
</Window>

Another way is to find the ancestor with defined type:

<TextBox Text="{Binding CodeBehindProperty, RelativeSource={RelativeSource AncestorType=Window}}"/>
Rekshino
  • 6,954
  • 2
  • 19
  • 44
  • Perfekt - this was exactly what I've searched for but didn't worked out properly. Thank you very much! And thanks also to the other comment distributors. – user1470240 Jun 29 '18 at 07:57