Почему мой настроенный WPF RadioButton не выглядит правильно? - PullRequest
2 голосов
/ 29 октября 2009

Я заменяю стиль переключателя на стиль флажка. Я знаю, что вы скажете, что это плохая идея, но она действительно должна работать таким образом. В любом случае, используя Expression Blend, я смог извлечь стиль CheckBox и применить его к RadioButton. Моя единственная проблема в том, что когда он рисует, границы нет. Кто-нибудь может сказать мне, почему? Вот код (ЭТО БЫЛО ОБНОВЛЕНО ПОСЛЕ ОРИГИНАЛЬНОГО ПОЧТЫ):

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Royale"
Title="Customized RadioButton" Width="496" ShowInTaskbar="True" ResizeMode="NoResize" Height="105">
<Window.Resources>
    <SolidColorBrush x:Key="CheckBoxStroke" Color="#8E8F8F"/>

    <Style x:Key="RadioButtonCheckBoxStyle" TargetType="{x:Type RadioButton}">
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        <Setter Property="Background" Value="#F4F4F4"/>
        <Setter Property="BorderBrush" Value="{StaticResource CheckBoxStroke}"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type RadioButton}">
                    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
                        <BulletDecorator Background="Transparent">
                            <BulletDecorator.Bullet>
                                <Microsoft_Windows_Themes:BulletChrome Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" IsChecked="{TemplateBinding IsChecked}" IsRound="false" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}"/>
                            </BulletDecorator.Bullet>
                            <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True"/>
                        </BulletDecorator>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="HasContent" Value="true">
                            <Setter Property="Padding" Value="4,0,0,0"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<StackPanel>
    <CheckBox Height="16" Name="checkBox1" Width="120">CheckBox</CheckBox>
    <RadioButton Height="16" Name="radioButton1" Width="120">RadioButton</RadioButton>
    <RadioButton Content="RadioButton with CheckBox Style" Margin="4" Style="{DynamicResource RadioButtonCheckBoxStyle}" FocusVisualStyle="{x:Null}" GroupName="Header" IsChecked="False" IsEnabled="True" HorizontalAlignment="Center" />
</StackPanel>

альтернативный текст http://img260.imageshack.us/img260/65/33733770.jpg

Чтобы увидеть, как это отображается, вставьте его в Visual Studio. Вы увидите, что настраиваемая кнопка радио выглядит неправильно. В нем отсутствуют обычные 3D-эффекты, которые обычно есть у CheckBox. Мне плевать на любой контент (у меня его не будет), я просто хочу, чтобы он выглядел как обычный CheckBox.

Ответы [ 2 ]

2 голосов
/ 29 октября 2009

Поскольку вы переопределяете шаблон, вам нужно присоединиться к свойствам класса самостоятельно.

Объявите границу в шаблоне следующим образом:

<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"/>

Также у вас есть небольшая ошибка. Вы определили установщик для "BorderBrush" несколько раз в своем стиле.

Редактировать: После просмотра вашего изображения вот ваша реальная проблема:

<Microsoft_Windows_Themes:BulletChrome Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" IsChecked="{TemplateBinding IsChecked}" IsRound="false" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}"/>

Вы пропустили BorderThickness в своей пуле. Он фактически устанавливал вашу толщину на 0, поэтому вы ничего не видели.

0 голосов
/ 29 октября 2009

Здесь может помочь изображение, но где вы ожидаете, что граница будет? Вы ожидаете границы вокруг всего контента? Единственная граница должна быть в соответствии с шаблоном, который вы используете, это где находится галочка. Если вы хотите создать рамку вокруг всего контента, вам нужно добавить Border в ControlTemplate следующим образом:

            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type RadioButton}">
                        <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
                            <BulletDecorator Background="Transparent">
                                <BulletDecorator.Bullet>
                                    <Microsoft_Windows_Themes:BulletChrome Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" IsChecked="{TemplateBinding IsChecked}" IsRound="false" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}"/>
                                </BulletDecorator.Bullet>
                                <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignme    nt}" RecognizesAccessKey="True"/>
                        </BulletDecorator>
                            <ControlTemplate.Triggers>
                                    <Trigger Property="HasContent" Value="true">
                                    <Setter Property="FocusVisualStyle" Value="{StaticResource CheckRadioFocusVisual}"/>
                                    <Setter Property="Padding" Value="4,0,0,0"/>
                                </Trigger>
                                <Trigger Property="IsEnabled" Value="false">
                                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>

Примечание: Вы установили FocusVisualStyle="{x:Null}" на самом флажке, но ваш шаблон изменяет это свойство в своем триггере HasContent. Если вы действительно не хотите использовать FocusVisualStyle, вам следует удалить этот установщик.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...