数据触发器中的标记扩展 [英] Markup Extension in Data Trigger

查看:21
本文介绍了数据触发器中的标记扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了翻译我的 WPF 应用程序,我使用了一个 Markup 扩展,它返回一个 Binding 对象.这允许我在应用程序运行时切换语言.我像这样使用这个标记:

To translate my WPF application I use a Markup extension which returns a Binding object. This allows me to switch the language while the application is running. I use this Markup like this:

<TextBlock Text="{t:Translate 'My String'}" />"

我想通过数据触发器更改按钮文本:

I would like to change a Buttons text through a data Trigger:

<Button>
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Template">
                <Setter.Value>
                    <!-- Custom control template, note the TextBlock formating -->
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Grid x:Name="ContentHolder">
                            <ContentPresenter TextBlock.Foreground="Red" TextBlock.FontWeight="Bold" />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <!-- Custom text triggered by Data Binding... -->
            <Style.Triggers>
                <DataTrigger Binding="{Binding MessageRowButton}" Value="Retry">
                    <Setter Property="Button.Content" Value="{t:Translate Test}" />
                </DataTrigger>
                <DataTrigger Binding="{Binding MessageRowButton}" Value="Acknowledge">
                    <Setter Property="Button.Content" Value="{t:Translate Test}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

这会导致以下异常:

无法在Setter"类型的Value"属性上设置Binding".只能在 DependencyObject 的 DependencyProperty 上设置绑定".

A 'Binding' cannot be set on the 'Value' property of type 'Setter'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

好的,这对我来说很有意义.我尝试在我的资源中定义 TextBlock 并在 DataTrigger 的 Setter 值中使用 {StaticResource MyResource} .但是当我这样做时,我的 Button 样式没有正确应用...

Ok, this make sense to me. I tried to define TextBlock in my Resource and use {StaticResource MyResource} in the DataTrigger's Setter Value. But when I do this, the style of my Button is not correctly applied...

如何使用我的标记扩展并更改按钮上的文本,而不会取消设置按钮内字符串样式的能力?

How can I work with my markup extension and change text on the button without destring the ability to style the string inside the button?

推荐答案

如果目标 (IProvideValueTarget.TargetObject) 是一个二传手.当样式应用于实际元素时,它将被重新评估.

Try returning the markup extension itself (this) if the target (IProvideValueTarget.TargetObject) is a setter. It will be reevaluated when the style is applied to an actual element.

public object ProvideValue(IServiceProvider serviceProvider)
{
    var pvt = service.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
    if (pvt.TargetObject is Setter)
        return this;

    ...
}

这篇关于数据触发器中的标记扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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