hypehuman
hypehuman

Reputation: 1369

Bind XAML property to arbitrary object from codebehind

I feel like this should be easy, but I've spent the last several hours trying solutions for this and nothing seems to work.

I have an object in XAML code, and I want to bind one of its properties to an object that was created in the c# codebehind. This is my strategy so far:

<setpwindows:ScalingWindow
    ...
>
    <setpwindows:ScalingWindow.Resources>
        <localwpf:ObjectProvider x:Key="locationProvider"/>
    </setpwindows:ScalingWindow.Resources>
    ...
        ...
            <DataGridTextColumn
                Header="Code Out"
                Binding="{Binding Source={StaticResource locationProvider}, Path=Obj.Name}"
            />
        ...
    ...
</setpwindows:ScalingWindow>

with ObjectProvider as follows:

class ObjectProvider : DependencyObject
{
    private object _obj;
    public object Obj
    {
        get { System.Diagnostics.Debug.WriteLine("Got object as " + _obj); return _obj; }
        set { _obj = value; System.Diagnostics.Debug.WriteLine("Set object to " + _obj); }
    }

    public static readonly DependencyProperty ObjProperty = DependencyProperty.Register("Obj", typeof(object), typeof(ObjectProvider));

    public ObjectProvider() {}
}

After the window is initialized, I set Obj like this:

WPFObjects.ObjectProvider locProv = this.FindResource("locationProvider") as WPFObjects.ObjectProvider;
locProv.Obj = _tempLocation;

This finally gives me no binding errors in the output window, but it doesn't actually bind anything. What is the standard way of doing this?

Upvotes: 0

Views: 384

Answers (1)

flq
flq

Reputation: 22859

This is all kinds of wrong, here just a few pointers:

  • dependency properties are targets of bindings, not sources.
  • do you set Obj anywhere? Does that what you set have a name property?

Then, learn about FrameworkElement.DataContext and the notification interfaces you can implement to notify dependency properties about changes in your data sources. see in other people's code hiw e.g. ViewModels look like and how they are bound to the UI.

Upvotes: 3

Related Questions