如何以编程方式将按钮内容绑定到动态资源

时间:2012-03-30 13:58:41

标签: c# wpf xaml binding code-behind

我正在尝试以编程方式将我的WPF按钮的Content属性绑定到我之前使用给定Path定义的动态资源(业务对象)。到目前为止,我尝试了以下方法,但没有运气:

我的业务对象被定义为资源:

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

我尝试以编程方式绑定到我的按钮:

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

但显然当我序列化到XAML时,它试图序列化整个Party对象,而我只想保留对我的资源的绑定引用,所以这个选项不起作用。 我的第二个选择是:

btn.SetResourceReference(ContentProperty,"myParty");

将序列化为XAML:

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

但我不知道如何指定我的Path = FullName,因此它可以显示Party.FullName而不是Party.Type()

关于如何实现这一目标的任何想法?

提前致谢,

1 个答案:

答案 0 :(得分:1)

将动态资源分配给DataContext,然后创建绑定而不设置Source属性

btn.SetResourceReference(DataContextProperty,"myParty");

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

现在,如果您已经按下按钮的DataContext,则需要设置Label作为按钮的内容,并在标签上设置资源和绑定。