【问题标题】:How to combine binding from custom data context with custom markup如何将自定义数据上下文的绑定与自定义标记结合起来
【发布时间】:2010-12-02 10:56:45
【问题描述】:

我想结合自定义数据上下文中的绑定,其中包含 ViewModel 类和 ResourceProvider 类。自定义数据上下文设置为窗口DataContext。

我就是这样用的:

<Button x:Name="btnShow" Content="Show" Command="{Binding View.HandleShow}"/>

哪个视图是 dataContext 的属性。我想使用最小标记通过自定义数据上下文进行本地化,并在我创建自己的数据上下文的代码中从其他源设置 ResourceProvider

有没有可能在类似于那行代码的东西中做到这一点:

 <TextBlock Text="{Binding Res.Key=test}" />

我的资源提供者从标记扩展继承了一个属性:键。

感谢您的建议

【问题讨论】:

    标签: wpf binding datacontext markup


    【解决方案1】:

    您可以使用以下代码创建自定义标记扩展:

    public class LocalizedBinding : MarkupExtension
    {
        public String Key { get; set; }
    
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            IProvideValueTarget target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
    
            //use target.TargetObject and target.TargetProperty to provide value based on Key
        }
    }
    

    并像这样使用它:

    <TextBlock Text="{local:LocalizedBinding Key=SomeKey}" />
    

    【讨论】:

      【解决方案2】:

      我尝试了该解决方案,但我更喜欢避免使用 local 前缀,因为本地化绑定来自不同的来源并使用 IoC 模式,因为我创建了 CustomDataContext

      【讨论】:

        猜你喜欢
        • 2013-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多