如何以编程方式访问样式中的元素?
问题描述:
我有以下WPF按钮样式:如何以编程方式访问样式中的元素?
<Style x:Key="myButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid Width="{Binding Width}" Height="{Binding Height}">
<Border Name="container" Background="{Binding Background}" CornerRadius="{Binding CornerRadius}">
<TextBlock Margin="10" FontFamily="Arial" FontWeight="Bold" TextAlignment="Left" HorizontalAlignment="Left" VerticalAlignment="Top" Width="Auto" FontSize="{Binding TextSize}" Foreground="White" Text="{Binding Text}" TextWrapping="Wrap"/>
</Border>
<Border Name="overlay" Background="Transparent" CornerRadius="{Binding CornerRadius}" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="overlay" Property="Opacity" Value="0.6" />
<Setter TargetName="overlay" Property="Background" Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
的问题是,虽然我的所有应用程序的按钮具有相同的风格,他们中的一些需要周围有边框。因此,我想知道是否可以访问我的风格的容器边框来设置其厚度和颜色?如果是这样,我该怎么做?
编辑:
我混madd0和Josh的建议,并创建了一个DataTrigger我的风格,里面搭配的结合,告诉我如果按钮应该或不应该有边框的属性。
最终的代码如下:
<Style x:Key="myButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid Width="{Binding Width}" Height="{Binding Height}">
<Border Name="container" Background="{Binding Background}" CornerRadius="{Binding CornerRadius}">
<TextBlock Margin="10" FontFamily="Arial" FontWeight="Bold" TextAlignment="Left" HorizontalAlignment="Left" VerticalAlignment="Top" Width="Auto" FontSize="{Binding TextSize}" Foreground="White" Text="{Binding Text}" TextWrapping="Wrap"/>
</Border>
<Border Name="overlay" Background="Transparent" CornerRadius="{Binding CornerRadius}" />
</Grid>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding Path=HasBorder}" Value="true">
<Setter TargetName="container" Property="BorderThickness" Value="{Binding BorderThickness}" />
<Setter TargetName="container" Property="BorderBrush" Value="{Binding BorderBrush}" />
</DataTrigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="overlay" Property="Opacity" Value="0.6" />
<Setter TargetName="overlay" Property="Background" Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
谢谢大家的帮助, Komyg
答
我认为,如果你扩展Button类,并给它一个新的布尔的DependencyProperty,基本上所有你需要要做的是给你的边界一个名字,然后在ControlTemplate.Triggers中,触发该布尔属性,使边界,你需要它在你的特殊情况。
它与您已经拥有IsPressed ControlTemplate触发器相似。
答
我不认为你真的需要访问你的控件模板属性。由于Button
已具有边框属性,因此您应该直接在按钮上设置这些属性。然后,将边框添加到您的ControlTemplate
,将其属性绑定到按钮的属性。
它是什么决定边框是否应该出现?如果你使用触发器做出这样的改变,它会更干净 – madd0