如何将按钮样式添加到wpf中的窗口资源中



我有一个滑动按钮,它有一个样式,里面有一个删除deffault鼠标悬停效果的内容模板,还有一个图像背景。我想在其他按钮上使用所有这些,所以我想把它放在我的windows.resources中,但当我尝试时,我总是给我各种各样的错误。有人能帮我吗?

这是代码:

<Button x:Name="button1"  HorizontalAlignment="Left" Margin="-352.388,147.206,0,136.193">
<Button.Background>
<ImageBrush ImageSource="button1.png"/>
</Button.Background>
<Button.RenderTransform>
<TranslateTransform />
</Button.RenderTransform>
<Button.Style>
<Style TargetType="Button">
<Setter Property="Width" Value="508"/>
<Setter Property="Height" Value="138"/>
<Setter Property="UseLayoutRounding" Value="True"/>
<Setter Property="ClipToBounds" Value="True"/>
<Setter Property ="Background">
<Setter.Value>
<ImageBrush ImageSource ="button.png "/>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Name="border" BorderThickness="0" BorderBrush="Black" Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Opacity" Value="0.8" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<EventTrigger RoutedEvent="MouseEnter">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="(Image.RenderTransform).(TranslateTransform.X)" From="0" To="190"  Duration="0:0:0.2" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="MouseLeave">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="(Image.RenderTransform).(TranslateTransform.X)" From="190" To="0"  Duration="0:0:0.3" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>

在您的窗口中,将样式放在里面,如下所示:

<Window.Resources>
<ResourceDictionary>
<Style x:Key="SlidingButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Width" Value="508" />
<Setter Property="Height" Value="138" />
<Setter Property="UseLayoutRounding" Value="True" />
<Setter Property="ClipToBounds" Value="True" />
<Setter Property ="Background">
<Setter.Value>
<ImageBrush ImageSource ="button.png "/>
</Setter.Value>
</Setter>
/*********rest of code*********/
</Style>
</ResourceDictionary>
</Window.Resources>

然后,您可以使用为样式指定的x:Key,在本例中为SlidingButtonStyle,对按钮进行如下样式设置:

<Button
Style="{StaticResource SlidingButtonStyle}"
/*****rest of code****/>
</Button>

为了更好地组织,您可以制作另一个文件作为ResourceDictionary,它可以包含多种样式。然后你可以将其包含在窗口或UserControl中,如下所示:

<Window.Resources>
<ResourceDictionary Source="WindowResources.xaml" />
</Window.Resources>

相关内容

  • 没有找到相关文章

最新更新