1

I am trying to bind programmatically the Content property of my WPF Button to a Dynamic Resource (Business Object) I have previously defined using a given Path. So far I tried the following approaches with no luck:

My Business Object is defined as a resource:

<Window.Resources>
   <env:PartyType x:Key="myParty" FullName="JOHN"/>
</Window.Resources>

I tried binding to my button programmatically like this:

        Binding binding = new Binding();
        binding.Source = this.Resources["myParty"];
        binding.Path = new PropertyPath("FullName");
        btn.SetBinding(ContentProperty, binding);

But apparently when I serialize to XAML its trying to serialize the whole Party Object, and I just want to keep a binding reference to my resource, so this option doesn't work. My second option was:

btn.SetResourceReference(ContentProperty,"myParty");

That gets serialized to XAML as:

<av:Button Content="{av:DynamicResource myParty}"/>

But I don't know how to specify my Path=FullName so it can display the Party.FullName and not the Party.Type().

Any ideas on how to achieve this?

Thanks in advance,

1 Answer 1

1

Assign the dynamic resource to the DataContext and then create your binding without setting the Source property

btn.SetResourceReference(DataContextProperty,"myParty");

Binding binding = new Binding();
binding.Path = new PropertyPath("FullName");
btn.SetBinding(ContentProperty, binding);

Now if you already depand on the button's DataContext, then you need set a Label as the button's content and set the resource and binding on the label.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Simon, that part worked fine. Now, I decided to set the DataContext in the XAML for the parent control (Canvas). Everything works fine, but when I Load the serialized XAML it doesn't show the bound data, any ideas on what could it be?
@AdolfoPerez, Does the serialized XAML include the binding? My only guess is that the binding is not being serialized.
Yes, the Serialized XAML includes the binding as follows: <av:Button Content="{av:Binding Path=FullName, Source={x:Null}}" When I inspect my regenerated object it does include the binding, but for some reason the Content is set to null
Hmm, try looking for binding errors in the output window. Some time back I wrote an article on debuggeing data bindings you can find it here, I think it should allow you to figure out why the binding doesn't work as expected.
I'll have to do that. Thanks again for all your help @SimonBangKerkildsen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.