【问题标题】:Custom Button Style Content property binding自定义按钮样式内容属性绑定
【发布时间】:2016-02-03 14:26:26
【问题描述】:

我有一个按钮的自定义样式

 <Style x:Key="CustomButton" TargetType="Button">
    <Setter Property="BorderBrush" Value="Black"/>
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="Content">
        <Setter.Value>
            <Grid>
                <Ellipse Width="40" Height="20" Fill="Yellow"/>
                <TextBlock Text="{Binding ****Bind to Content Property on button***}"/>
            </Grid>               
        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border>
                    <Border.Background>
                        <SolidColorBrush x:Name="CustomBackground"
                                         Color="LightBlue"/>
                    </Border.Background>

                    <ContentPresenter/>
                </Border>                   
            </ControlTemplate>               
        </Setter.Value>
    </Setter>
</Style>

我的Content 属性有一个复杂的对象。 content 属性的值有一个TextBlock。是否可以将TextblockText 属性绑定到ButtonContent 属性

<Button Style="{StaticResource CustomButton}"
                Content="Bound to Textblock in style"/>

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    只需使用TemplateBindingTextBlockText 绑定到Button Content

        <Style x:Key="CustomButton" TargetType="Button">
            <Setter Property="BorderBrush" Value="Black"/>
            <Setter Property="Foreground" Value="White"/>
    
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border>
                            <Border.Background>
                                <SolidColorBrush x:Name="CustomBackground"
                                         Color="LightBlue"/>
                            </Border.Background>
    
                            <Grid>
                                <Ellipse Width="40" Height="20" Fill="Yellow"/>
                                <TextBlock Text="{TemplateBinding Content}"/>
                            </Grid>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    

    【讨论】:

    • 当我使用您的代码示例时,我收到以下错误:'{DependencyProperty.UnsetValue}' is not a valid value for the 'System.Windows.Controls.Control.Template' property on a Setter. 这仅在我使用TemplateBinding 时。 Content 也不会与智能感知一起显示。仅限 nameuidContentStringFormat
    • 它在我的最后工作正常!您确实将 ContentPresenter 替换为实际内容,是吗?
    猜你喜欢
    • 1970-01-01
    • 2018-02-07
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多