I'd like to be able to use arbitrary C# expressions in XAML. Usually this would be to compute a property for a UI element based on two bound values.
For example calculating the width of a UI element based on two other properties.
This is a contrived example of what I'd like the XAML to look like:
<TextBox
x:Name="textBox1"
/>
<TextBox
x:Name="textBox2"
/>
<Rectangle
Height={Double.Parse(textBox1.Text) + Double.Parse(textBox2.Text)}
/>
Of course there is no built-in way of doing this in XAML.
I know that I could use a MultiBinding combined with a custom converter and this is usually the way I do this kind of thing. However it seems to me that it would be so much simpler to just include some C# code in the XAML and I was wondering if anyone out there had already solved this problem with a XAML extension or something else.
You embed C# code into XAML like this:
<x:Code>
<![CDATA[
void ButtonOnClick(object sender, RoutedEventArgs args)
{
Button btn = sender as Button;
MessageBox.Show("The button labeled '" +
btn.Content +
"' has been clicked.","Information Message");
}
]]>
</x:Code>
But this approach is not recommended at all because it mixes the pure presentation layer with business logic.
I've seen custom Xaml converters that take IronPython code and Invoke the DLR. It's not quite C#, but its certainly is less ugly than the approach of using [CDATA] tags.
http://pybinding.codeplex.com/
This is the link to an open source project on the matter.
Wrap your expression into a public property and bind to that property.
In C# codebehind:
public double Heigth
{
get { return Double.Parse(textBox1.Text) + Double.Parse(textBox2.Text); }
}
In XAML:
<Rectangle Height={Binding Heigth} />
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