1

Hello I have a custom control. This custom control has it's DataContext set to an entity. In my custom control I then bind some TextBlocks to various properties of this entity.

I would also like to bind a TextBlock to a property of the control's class. I do not want/need to set this property through the XAML.

Something like

<TextBlock Content="{Binding Path=MyControl.Property}" />

Right now, my it seems to be trying to use the bound entity to resolve this binding, rather than my custom control's class.

Azhar
  • 20,500
  • 38
  • 146
  • 211
Gilles
  • 5,269
  • 4
  • 34
  • 66

3 Answers3

2

You can use RelativeSource in your Binding

{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type MyControl}}}

Also you can see more in this question

Community
  • 1
  • 1
alpha-mouse
  • 4,953
  • 24
  • 36
  • This will work in WPF, but does not work in Silverlight. In Silverlight the simplest way is to not use bindings at all and to explicitly set from the code (assuming custom `Control` and not `UserControl` – Stephan Nov 17 '10 at 14:27
  • Yep, you are right. Silverlight doesn't support this. I missed this "silverlight" tag on the question. – alpha-mouse Nov 17 '10 at 14:35
1

In your custom control you should expose a dependency property with the property you want to bind.

Also, you probably don't want to bind the content of the textblock, you want to bind the text:

<TextBlock Text="{Binding Path=MyControl.Property}" />
dcarneiro
  • 7,060
  • 11
  • 51
  • 74
1

If the TextBlock is within the ControlTemplate of your custom control then you could create a DP on your custom control and then template bind to it. e.g.

<TextBlock Text="{TemplateBinding CustomControlPropertyName}" />
AndrewS
  • 6,054
  • 24
  • 31