Binding to a custom control property

拜拜、爱过 提交于 2019-12-11 06:57:40

问题


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.


回答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}" />



回答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




回答3:


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}" />


来源:https://stackoverflow.com/questions/4205144/binding-to-a-custom-control-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!