views:

717

answers:

2

Can an object created in the code (ie C#) be used for binding in the XAML?

For example:

public class MyForm
{
    private MyComplexObject complexObject;

    public MyForm()
    {
        InitializeComponent();
    }

    public OnButtonClick(object sender, RoutedEventArgs e)
    {
        complexObject = new MyComplexObject();
    }
}

complexObject is not created till a button is clicked. But once that button is clicked I would like to have a text box that is bound to complexObject.ID start showing the Id.

I would like to do that in the XAML if that is possible.

Can this be done? If so, how?

+2  A: 

One possibility would be to have your XAML bind to a property on your code behind. The getter for that property would return complexObject.ID, if complexObject != null. Otherwise, it returns something "default", whether that's null or 0 or default(ID's type). Similarly, the setter for that property would assign value to complexObject.ID if complexObject is, again, not null.

public int ID
{
    get
    {
        if (complexObject != null)
            return complexObject.ID;
        return 0; // or null or some appropriate default
    }
    set
    {
        if (complexObject != null)
            complexObject.ID = value;
    }
}
JMD
+1 was going to suggest instantiating a wrapper object that contained a MyComplexObject object - but your way is cleaner :)
IanR
+4  A: 

Yes, this can be done, binding to a property that you update with the desired value. I'd suggest you look into the MVVM pattern (Model-View-ViewModel), which is really useful for structuring this nicely working with WPF. Check out this video for a nice overview: MVVM video

Using MMVM you would create a class which would be the ViewModel class. This one would typically be set to the DataContext of the View. Having done so you could add dynamic references to the other properties of the class, e.g. binding your text field to some property holding the Id og the ComplexObject. If your ViewModel class had a property ComplexObject, which again had a property ID you'd simply bind to the object like this:

<TextBlock Text="{Binding ComplexObject.ID}" />

Having this you could trigger creation of your ComplexObject from mouse click, which you should ideally set up as a command binding. Also note that the ViewModel class (or whoever is holding the ComplexObject needs to notify the View when the object has been set. This can either be done by making the ComplexObject a DependencyProperty or by making the class holding the property implement the INotifyPropertyChanged interface - giving it the PropertyChanged function to trigger the changed event. I prefer the latter.

stiank81