Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - databinding to a property of same control

I have a control (let's say a textbox) and I want bind the value of one property (let's say tooltip) to value of another property in same control(let's say text).

i want something like belowing but I dont know how can I bind the tooltip to text of same control :

<textBox text="abc" tooltip={Binding ???} />
like image 589
Asha Avatar asked Oct 19 '10 12:10

Asha


People also ask

What is two way binding WPF?

Its very easy to do in WPF in comparison of windows Application programming. Two way binding is used when we want to update some controls property when some other related controls property change and when source property change the actual control also updates its property.

What is oneway binding WPF?

In One Way binding, source control updates the target control, which means if you change the value of the source control, it will update the value of the target control. So, in our example, if we change the value of the slider control, it will update the textbox value, as shown below.

What is binding source in WPF?

A binding source is usually a property on an object so you need to provide both the data source object and the data source property in your binding XAML. In the above example the ElementName attribute signifies that you want data from another element on the page and the Path signifies the appropriate property.

What is DataContext in WPF?

The DataContext property is the default source of your bindings, unless you specifically declare another source, like we did in the previous chapter with the ElementName property. It's defined on the FrameworkElement class, which most UI controls, including the WPF Window, inherits from.


2 Answers

Use RelativeSource:

<TextBox Text="abc" ToolTip="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Text}" />
like image 110
ThomasAndersson Avatar answered Oct 07 '22 02:10

ThomasAndersson


If you use the MVVM pattern you can expose a property on the ViewModel and then bind both to the same property:

<textBox text="{Binding Text}" tooltip="{Binding Text}" />

And in the ViewModel:

public string Text { get return "abc"; }

This allows you to unit test that the value presented is correct.

like image 27
Jackson Pope Avatar answered Oct 07 '22 02:10

Jackson Pope