Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an existing way to use arbitrary C# expressions in XAML?

Tags:

c#

wpf

xaml

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.

like image 825
Ashley Davis Avatar asked Dec 03 '10 13:12

Ashley Davis


3 Answers

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.

like image 163
Liviu Mandras Avatar answered Sep 25 '22 11:09

Liviu Mandras


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.

like image 36
Michael B Avatar answered Sep 22 '22 11:09

Michael B


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} />
like image 32
VVS Avatar answered Sep 25 '22 11:09

VVS