Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding to Self/'this' in XAML

Tags:

c#

wpf

xaml

Simple WPF/XAML question. In XAML, how do I reference the Self/this object in a given context? In a very basic app with a main window, one control, and a coded C# property of the window, I want to bind a property of the control to the hand coded property of the window.

In code, this is very easy - in the Window's constructor, I added this:

Binding bind = new Binding(); bind.Source = this; bind.Path = new PropertyPath("ButtonWidth"); button1.SetBinding(WidthProperty, bind); 

Obviously, I have a property called ButtonWidth, and a control called button1. I can't figure out how to do this in XAML. Various attempts like the following example have not worked:

<Button x:Name="button1" Width="{Binding Source=Self Path=ButtonWidth}"/>  <Button x:Name="button1" Width="{Binding RelativeSource={RelativeSource Self} Path=ButtonWidth}"/>  

etc

Thanks

like image 451
Tom Davies Avatar asked Oct 01 '10 09:10

Tom Davies


People also ask

How do I bind data in XAML?

Data binding is a mechanism in XAML applications that provides a simple and easy way for Windows Runtime Apps using partial classes to display and interact with data. The management of data is entirely separated from the way the data is displayed in this mechanism.

What does binding mean in WPF?

Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface.

How many types of binding are there in WPF?

WPF binding offers four types of Binding.


2 Answers

First use a comma between the RelativeSource and Path in your Binding:

<Button x:Name="button1" Width="{Binding RelativeSource={RelativeSource Self},                                  Path=ButtonWidth}"/>  

Secondly, the RelativeSource binds to the Button. Button has no property called ButtonWidth. I am guessing you need to Bind to your parent control.

So try this RelativeSource binding:

<Button x:Name="button1" Width="{Binding RelativeSource=     {RelativeSource FindAncestor, AncestorType={x:Type YourNamespace:YourParentControl}},      Path=ButtonWidth}"/>  
like image 172
Arcturus Avatar answered Sep 20 '22 07:09

Arcturus


I think what you are looking for is this:

<Window x:Class = "blah blah all the regular stuff"  DataContext="{Binding RelativeSource={RelativeSource Self}}"  > 
like image 22
Clint StLaurent Avatar answered Sep 22 '22 07:09

Clint StLaurent