WPF,基于Button的自定义控件,使用ResourceDictionary定义其样式 [英] WPF, Custom Control based on Button using a ResourceDictionary to define it's style
问题描述
有人知道如何基于从ResourceDictionary中提取其样式的Button定义自定义控件吗?
我想做的是定义一个类似于拨动开关的按钮,它显示一个默认的图像,然后当用户按下它时,它将显示第二个图像(在本例中为路径") ,然后在用户再次按下时返回到第一个.
我需要一个自定义控件,以便在发生某些情况时可以以编程方式切换按钮.它的工作方式类似于任何Media Player上的播放"按钮.
任何建议都是不错的选择.
Does anyone know how to define a Custom Control based on a Button that pulls it''s Style from a ResourceDictionary?
What I''m trying to do is define a Button that is sort of like a toggle switch, it has a default Image displayed, then when the user presses it, it will show the second Image (which is a Path in this case), then revert to the first once the user presses it again.
I need a custom control so that I can programatically toggle the button if certain things happen. It would work sort of like the play button on any Media Player.
Any advice would be great.
推荐答案
正如我所意识到的,您需要一个行为与
ToggleButton
完全一样但外观不同的控件. -您不需要为此使用自定义控件.
As I realized, you need a control that behaves exactly like a
ToggleButton
but, looks different. - You don''t need a custom control for that purpose.
您可以只创建一个Style
并将其设置为您的ToggleButton
,就像下面的Grid
一样:
You can just create a Style
and set it to your ToggleButton
, like in the following Grid
:
<Grid>
<Grid.Resources>
<Style x:Key="myToggleButtonStyle"
TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Grid>
<Grid x:Name="uncheckedGrid">
<Rectangle Stroke="DarkGreen" StrokeThickness="2"
Fill="LightGreen" />
<TextBlock Text="Unchecked" Margin="20" />
</Grid>
<Grid x:Name="checkedGrid" Visibility="Collapsed">
<Ellipse Stroke="DarkRed" StrokeThickness="2"
Fill="Salmon" />
<TextBlock Text="Checked" Margin="20" />
</Grid>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Visibility" TargetName="uncheckedGrid"
Value="Collapsed" />
<Setter Property="Visibility" TargetName="checkedGrid"
Value="Visible" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources>
<ToggleButton Style="{StaticResource myToggleButtonStyle}"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Grid>
在此Grid
中,有一个ToggleButton
,当未选中时显示Rectangle
,在选中时显示Ellipse
.您可以用图像替换Rectangle
和Ellipse
.
In this Grid
, there is a ToggleButton
that shows a Rectangle
when it is unchecked and, shows an Ellipse
when it is checked. You can replace the Rectangle
and the Ellipse
with your images.
这篇关于WPF,基于Button的自定义控件,使用ResourceDictionary定义其样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!