在wpf xaml中更改继承样式的控件属性

时间:2014-03-18 17:12:39

标签: wpf xaml wpf-controls

我定义了这些样式:

<Style x:Key="ImgButton" TargetType="Button">
    <Setter Property="Background" Value="Transparent"></Setter>
    <Setter Property="Height" Value="30"></Setter>
</Style>
<Style x:Key="ImgButtonWithText" TargetType="{x:Type Button}" BasedOn="{StaticResource ImgButton}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Image Name="ButtonImage" Stretch="Uniform" Height="20" Width="20" Source="">
                    </Image>
                    <TextBlock Name="ButtonText" Margin="4,0" VerticalAlignment="Center" Text=""></TextBlock>
                </StackPanel>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

我想创建另一个样式,LoginButtonWithText(如下所示),它基于ImgButtonWithText,并在ImgButtonWithText样式中设置ButtonImage控件的Source属性的值。我想对ButtonText文本块的Text属性执行相同的操作。

<Style x:Key="LoginButtonWithText" TargetType="{x:Type Button}" BasedOn="{StaticResource ImgButtonWithText}">
    <Setter Property="ToolTip" Value="Login"></Setter>
    <Setter Property="IsDefault" Value="True"></Setter>
    //How do I set the Image Source value and TextBlock Text value here?
</Style>

我发现了this个问题,但它似乎并不是我正在寻找的。如何从继承的样式更改子控件的值,还是我做错了?

1 个答案:

答案 0 :(得分:0)

似乎我想要做的事情并不完全可能,但我已经完成了定义图像按钮样式的下一个最好的事情,以便在从ImgButtonWithText继承的所有样式中使用:

<Style x:Key="ImgButton" TargetType="Button">
    <Setter Property="Background" Value="Transparent"></Setter>
    <Setter Property="Height" Value="30"></Setter>
</Style>
<Style x:Key="ButtonImage" TargetType="Image">
    <Setter Property="Height" Value="20"></Setter>
    <Setter Property="Width" Value="20"></Setter>
    <Setter Property="Stretch" Value="Uniform"></Setter>
</Style>
<Style x:Key="ButtonText" TargetType="TextBlock">
    <Setter Property="Margin" Value="4,0"></Setter>
    <Setter Property="VerticalAlignment" Value="Center"></Setter>
</Style>
<Style x:Key="LoginButtonWithText" TargetType="{x:Type Button}" BasedOn="{StaticResource ImgButton}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Image Name="ButtonImage" Style="{StaticResource ButtonImage}" Source="../Images/login.png">
                    </Image>
                    <TextBlock Name="ButtonText" Style="{StaticResource ButtonText}" Text="Let's Go"></TextBlock>
                </StackPanel>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>