Ton*_*ile 2 wpf custom-controls controltemplate
我是WPF的新手,我不知道该怎么做我想做的事.
我已经构建了一个自定义控件,我称之为音量控制.它有2个RepeatButtons,1个用于增加Volume属性的值,1个用于减少它,还有一个ProgressBar用于给出当前Volume的可视化表示.该控件具有Orientation类型的名为"Orientation"的属性.当它是水平的时候,我希望控制以一种方式绘制,当它是垂直时,我希望它看起来不同.
在水平模式下,控件将简单地将3个控件放在水平StackPanel中.垂直外观有点复杂,因为它有一个网格,有2列和2行.2个RepeatButtons在左侧堆叠在一起,而ProgressBar跨越两行并且在右侧.
我似乎无法弄清楚如何使控件根据Orientation属性的值更改其外观.这是我到目前为止所得到的:
<Style x:Key="Horizontal" TargetType="{x:Type cs:VolumeControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type cs:VolumeControl}">
<StackPanel Orientation="Horizontal">
...
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="Vertical" TargetType="{x:Type cs:VolumeControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type cs:VolumeControl}">
<Grid>
...
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)
我知道我需要这样的东西来定义默认模板和Orientation属性的必要触发器:
<Style TargetType="{x:Type cs:VolumeControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type cs:VolumeControl}">
<ControlTemplate.Triggers>
<Trigger Property="Orientation" Value="Horizontal">
???
</Trigger>
<Trigger Property="Orientation" Value="Vertical">
???
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter.Value>
</Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)
我不知道在两个Trigger标签中加入什么来使它工作.或者即使我已经把它弄好了.
我查看了ProgressBar的模板,当Orientation设置为Vertical时,它使用RotationTransform垂直绘制控件.我不能这样做,因为意图是以不同的布局绘制控件.
任何帮助表示赞赏.
托尼
小智 5
创建2个控件模板
<ControlTemplate x:Key="Horizontal" TargetType={x:Type cs:VolumeControl}....
<ControlTemplate x:Key="Vertical" TargetType={x:Type cs:VolumeControl}...
Run Code Online (Sandbox Code Playgroud)
然后创建一个样式并使用它来通过触发器切换模板
<Style TargetType={x:Type cs:VolumeControl}>
<Style.Triggers>
<Trigger Property="Orientation" Value="Horizontal">
<Setter Property="Template" Value={StaticResource Horizontal}" />
</Trigger>
<Trigger Property="Orientation" Value="Vertical">
<Setter Property="Template" Value={StaticResource Vertical}" />
</Trigger>
</Style.Triggers>
</Style>
Run Code Online (Sandbox Code Playgroud)
对我来说就像一个魅力:)