为什么不应用默认样式?

时间:2014-03-04 03:05:29

标签: c# .net wpf

出于某种原因,我做了一个CustomButton课程。 我尝试将默认的Button样式应用于CustomButton

<my:CustomButton  Style={StaticResource {x:Type Button}}/>

但这不起作用。你觉得为什么?


<Button x:Name="button1" />
<CustomButton Style={Binding Style, ElementName=button1} />

这很有效。但我认为这不是很好。

1 个答案:

答案 0 :(得分:0)

您必须为按钮创建样式并应用样式。

如果您删除x:Key="ButtonStyle1",那么您的样式将应用于您的所有CustomButton,当然如果您的按钮样式已包含

<Style x:Key="ButtonStyle1"  TargetType="{x:Type yourNameSpace:CustomButton}">
        <Setter Property="Foreground"
                Value="Red" />
        <Setter Property="Margin"
                Value="10" />
    </Style>

<yourNameSpace:CustomButton Width="100" Height="100"  Style="{StaticResource ButtonStyle1}"> </yourNameSpace:CustomButton>

您应该检查Styling and Templating和此Tutorial

Style={StaticResource {x:Type Button}}这是错误的,期望资源不是类型的密钥。

来自文档StaticResource

Provides a value for any XAML property attribute by looking up a reference to an already defined resource. Lookup behavior for that resource is analogous to load-time lookup, which will look for resources that were previously loaded from the markup of the current XAML page as well as other application sources, and will generate that resource value as the property value in the run-time objects.