tags:

views:

41

answers:

2

Hi. 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

A: 

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}"/> 
Arcturus
A: 

Great, thanks. That works. It's a bit verbose though - could it be done instead by setting the DataContext property of the owning window? If my xaml simply reads:

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

Then I can make this work by adding the following line to the constructor of the Window:

DataConext=this;

Can I do something similar in xaml, something like this:

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

Various attempts at setting the DataContext to Self/'this' have not worked for me.

Tom Davies
@Tom Davies, you should rather add this to your original question. It makes it easier for future viewers to follow the complete question and subsequent answers.
Chris Taylor