【问题标题】:How do I bind template with style?如何将模板与样式绑定?
【发布时间】:2012-06-22 15:25:59
【问题描述】:

我有一个 C# WPF 应用程序,我需要在其中创建一堆不同颜色的图像/文本按钮。为此,我创建了一个从 Button 类派生的 ImageButton。

我希望我的按钮有圆角,所以我创建了以下控件模板:

    <ControlTemplate x:Key="RoundedButtonTemplate" TargetType="{x:Type MyProject:ImageButton}">
        <Grid>
            <Border x:Name="border" Background="WHAT DO I PUT HERE?" CornerRadius="10"/>
        </Grid>         
    </ControlTemplate>

现在我希望能够轻松更改上方边框的颜色,只需更改 XAML 中的样式即可。我定义了以下样式。

绿色按钮样式:

    <Style x:Key="GreenButtonStyle" TargetType="{x:Type MyProject:ImageButton}">
        <Setter Property="Background" Value="{DynamicResource GreenButtonBrush}"/>
RoundedButtonTemplate}"/>
    </Style>

蓝色按钮样式:

    <Style x:Key="GreenButtonStyle" TargetType="{x:Type MyProject:ImageButton}">
        <Setter Property="Background" Value="{DynamicResource BlueButtonBrush}"/>
RoundedButtonTemplate}"/>
    </Style>

我的客户端代码如下所示:

<local:ImageButton HorizontalAlignment="Left" Margin="24,19.234,0,20" Width="97" Grid.Row="3" Style="{DynamicResource GreenButtonStyle}" Template="{DynamicResource RoundedButtonTemplate}"/>

我的问题是如何让模板知道要使用哪种样式?我尝试将以下属性添加到我的样式中,但没有太大成功:

<Setter Property="Template" Value="{DynamicResource RoundedButtonTemplate}"/>

【问题讨论】:

    标签: c# wpf templates xaml styles


    【解决方案1】:

    我猜 ImageButton 继承自 UserControl,因为这是一个复合控件。如果没有,你可能应该。 MSDN 讨论了从 Control 与 UserControl 继承。我会把 Border 放在那里,放在 Button 和 TextBlock 之类的里面。

    一种方法是在新的 ImageButton 类上定义一个依赖属性,例如“BorderBackground”。当您设置它时,您可以将其链接起来以更改边框的背景颜色。如果你愿意,我可以提供示例代码。

    当您设置样式时,目标属性将是“BorderBackground”。这将消除对 ControlTemplate 进行任何更改的需要,而我通常会尽量避免。

    这有帮助吗?

    或者回答您最初的问题,我不确定模板是否知道如何应用样式,因为您的样式针对 ImageButton 控件的背景,而不是边框​​控件的背景。

    【讨论】:

      【解决方案2】:

      我想我明白了。所需要的只是将以下文本放入我的模板定义中:

      Background="{TemplateBinding Background}"
      

      更多信息可以在这篇文章中找到: TemplateBinding: a bridge between styles and templates

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-09
        • 1970-01-01
        • 1970-01-01
        • 2019-03-20
        • 2015-07-03
        • 2011-06-04
        • 1970-01-01
        相关资源
        最近更新 更多