中为样式使用绑定

中为样式使用绑定

本文介绍了Silverlight:如何在 setter 中为样式使用绑定(或等效的解决方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果回答这个问题的人是对的,你不能绑定为 Silverlight 样式中 setter 中的值.真可惜,因为我有 4 个文本块,它们的 Opacity 属性都使用完全相同的绑定.无论如何,在某种意义上样式"它们的 Opacity 属性,以便它们四个都指向相同的绑定?否则,我必须单独设置每个 Opacity 属性.就我而言,情况更糟 - 所有四个都共享其他属性绑定,这意味着每个 TextBlock 声明都非常长,但它们几乎都相同(即它们的属性绑定).我知道我可以在代码隐藏中简洁地设置他们所有的共享属性绑定,但我想要一个 XAML 解决方案,如果有的话.

If the person who answered this question is right, you cannot put a binding as the value in a setter in a style in Silverlight. Which is a shame, because I have 4 textblocks that all use the exact same binding for their Opacity property. Is there anyway to in a sense "style" their Opacity property so that all four of them point to the same binding? Otherwise, I have to set each Opacity property individually. In my case it's even worse - all four share other property bindings as well, which means each TextBlock declaration is pretty dang long, and yet they're all virtually the same (their property bindings, that is). I know I could concisely set all their shared property bindings in the code-behind, but I'd like a XAML solution if there is one.

谢谢!

推荐答案

这是它的完成方式.您使用 ContentControl 并为其指定一个 ControlTemplate 作为静态资源:-

Here is how its done. You use a ContentControl and specify a ControlTemplate for it as a static resource:-

<Grid.Resources>
    <ControlTemplate x:Key="CommonTextBlock" TargetType="ContentControl">
        <TextBlock Opacity="{Binding SomeOpacity}" Text="{TemplateBinding Content}" />
    </ControlTemplate>
<Grid.Resource>
<ContentControl Content="{Binding SomeTextValue}" Template="{StaticResource CommonTextBlock}" />
<ContentControl Content="{Binding SomeOtherTextValue}" Template="{StaticResource CommonTextBlock}" />

现在您可以根据需要将其他属性绑定到控制模板.

Now you can bung as may other properties with bindings in to the Control Template as you want.

这种方法可以扩展到Style:-

This approach could be extended to Style:-

<Grid.Resources>
    <ControlTemplate x:Key="CommonTextBlock" TargetType="ContentControl">
        <TextBlock Opacity="{Binding SomeOpacity}" Text="{TemplateBinding Content}" />
    </ControlTemplate>
    <Style x:Key="CommonTextBlockStyle" TargetType="ContentControl">
       <Setter Property="Template" Value="{StaticResource CommonTextBlock}" />
       <Setter Property="Foreground" Value="Blue" />
    </Style>
<Grid.Resource>
<ContentControl Content="{Binding SomeTextValue}" Style="{StaticResource CommonTextBlockStyle}" />
<ContentControl Content="{Binding SomeOtherTextValue}" Style="{StaticResource CommonTextBlockStyle}" />

这篇关于Silverlight:如何在 setter 中为样式使用绑定(或等效的解决方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 00:55