作为资源绑定 [英] Binding as a Resource

查看:42
本文介绍了作为资源绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将 Binding 定义为 Resource,然后将其与不同的 Controls 属性重用吗?

Can I define a Binding as a Resource and then reuse it with different Controls properties?

示例:

绑定:

<Window.Resources>        
    <Binding x:Key="MyBinding" Path="MyProperty" Mode="TwoWay" />
</Window.Resources>

在 XAML 中重用:

<TextBox Text="{StaticResource MyBinding}" />

在如上所述声明 Binding 后,我得到了错误:

After declaring Binding as above I got the error:

"当前不存在名称 'InitializeComponent'上下文"

"The name 'InitializeComponent' does not exist in the current context"

有没有办法在不同的上下文中重用相同的Binding?

Is there any way to reuse the same Binding in different contexts?

推荐答案

直接回答您的问题是是的,您可以将绑定定义为资源".这里的问题是你如何使用它?一种可能性是创建一个扩展类,从资源中提取绑定并应用它:

Direct answer to your question is "yes, you can define a binding as a resource". The problem here is how do you then make any use of it? One possibility is to create an extension class which would pull the binding from the resources and apply it:

public class BindingResourceExtension : StaticResourceExtension
{
    public BindingResourceExtension() : base() { }

    public BindingResourceExtension(object resourceKey) : base(resourceKey) { }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var binding = base.ProvideValue(serviceProvider) as BindingBase;
        if (binding != null)
            return binding.ProvideValue(serviceProvider);
        else
            return null; //or throw an exception
    }
}

使用示例:

<Window.Resources>
    <ResourceDictionary>
        <Binding x:Key="MyBinding" Path="MyProperty" Mode="TwoWay" />
    </ResourceDictionary>
</Window.Resources>

(...)

<TextBox Text="{ns:BindingResource MyBinding}" />

这个解决方案可以用于 MultiBinding吗?

是的,它可以:

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="First: {0}, Second: {1}">
            <Binding Path="SomeProperty" />
            <ns:BindingResource ResourceKey="MyBinding" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

然而,这有一个缺点 - 尽管一切都可以在运行时运行,XAML 设计器会抱怨 BindingResourceExtension 不是正确的类型,可以放入MultiBinding.Bindings 集合.但是,幸运的是,有一个快速的解决方案 - 只需使用 StaticResourceExtension 代替!所以这虽然在运行时功能上是等效的,但会被设计者接受:

There is however one drawback to this - although everything will work in run-time, the XAML Designer will complain that BindingResourceExtension is not of proper type to be put in the MultiBinding.Bindings collection. But, thankfully, there is a quick solution - simply use StaticResourceExtension instead! So this, while being functionally equivalent in run-time, will be accepted by the designer:

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="First: {0}, Second: {1}">
            <Binding Path="SomeProperty" />
            <StaticResource ResourceKey="MyBinding" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

这篇关于作为资源绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆