For some reason, I made a CustomButton class. I tried to apply the default Button style to a CustomButton.

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

But this doesn't work. Do you think why?


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

This works well. But I think it's not very good.

有帮助吗?

解决方案

You have to create a style for your button and apply the style.

If you remove x:Key="ButtonStyle1" then your style will be applied to all your CustomButton, of course if your style for the button is included

<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>

You should check Styling and Templating and this Tutorial

Style={StaticResource {x:Type Button}} this is wrong is expecting a key for a resource not a type.

From documentation 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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top