Binding something in your XAML file to a property in your underlying partial class is pretty easy once you know the trick. You only have to name your XAML base object. For example, here is a PhoneApplicationPage declaration:
<phone:PhoneApplicationPage
x:Class="MyApp.MySamplePage"
x:Name="Self"
>
...
</phone:PhoneApplicationPage>
x:Class="MyApp.MySamplePage"
x:Name="Self"
>
...
</phone:PhoneApplicationPage>
I always give “Self” as my object name as I find using “Self” in the binding declaration makes the binding obvious but you can use the name you want. My example is for a Windows Phone application however the same mechanism works for any XAML desktop application.
Then you define a property in your class, for example
namespace MyApp
{
public partial class MySamplePage : PhoneApplicationPage
{
public String MyStringProperty { get { return "Binded string"; } }
...
}
}
{
public partial class MySamplePage : PhoneApplicationPage
{
public String MyStringProperty { get { return "Binded string"; } }
...
}
}
Now, you can use some binding magic in your XAML file to map a node property to a class property :
<TextBlock Text="{Binding MyStringProperty, ElementName=Self}" />
And VoilĂ !
I tried this technique (and a few others), but it doesn’t seem to work for me – any ideas what I might be missing?
Correction – it works in the running code, but not (apparently) in the designer. Thanks for this!