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
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.
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.
WPF binding offers four types of Binding.
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}"/>
I think what you are looking for is this:
<Window x:Class = "blah blah all the regular stuff" DataContext="{Binding RelativeSource={RelativeSource Self}}" >
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With