切换按钮样式与文本和图像

时间:2016-07-18 08:12:08

标签: c# wpf

我有下一个风格:

<Style x:Key="Style_MainButtons" TargetType="ToggleButton">
    <Setter Property="Width" Value="110" />
    <Setter Property="Height" Value="110" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ToggleButton}">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <TextBlock x:Name="Text" HorizontalAlignment="Center" />
                    <Image x:Name="Image" Grid.Row="1" />
                </Grid>
                <ControlTemplate.Triggers>                              
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

由于使用此样式的切换按钮很少,并且每个按钮都有不同的文本和图像,因此如何在下一个代码中从样式中调用“TextBlock”和“Image”?

<ToggleButton x:Name="btnHorizontal" 
              Style="{StaticResource Style_MainButtons}"
              Grid.Column="0" 
              Grid.Row="1" 
              Checked ="SetVersion" 
              Unchecked ="SetVersion" 
              IsChecked="True" >
</ToggleButton>

1 个答案:

答案 0 :(得分:1)

您可以这样做:

<强>风格

<Style TargetType="ToggleButton">
                <Setter Property="Width" Value="110" />
                <Setter Property="Height" Value="110" />
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type ToggleButton}">
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto" />
                                    <RowDefinition />
                                </Grid.RowDefinitions>
                                <TextBlock x:Name="Text" HorizontalAlignment="Center" Text="{TemplateBinding Content}"/>
                                <Image x:Name="Image" Grid.Row="1" Source="{TemplateBinding Tag}" />
                            </Grid>
                            <ControlTemplate.Triggers>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>

<强>用法

<ToggleButton Content="Text" Tag="{Binding Path=Source, Source={StaticResource Image}}"></ToggleButton>
<ToggleButton Content="Another Text" Tag="{Binding Path=Source, Source={StaticResource Image}}"></ToggleButton>

注意:将我的标记绑定替换为有效的绑定到实际的ImageSource