Search code examples
c#wpfxamlbindingcode-behind

How to bind button Content to Dynamic Resource programmatically


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,


Solution

  • 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.