Frage

I'm attempting to create a control template for the Silverlight RadioButton, using a ToggleButton for each item. The problem I'm running into is that the selection mechanism appears to be broken. Here's the (simplified) style I'm using:

<Style TargetType="RadioButton">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="RadioButton">
                <Grid>
                    <ToggleButton x:Name="toggle" 
                                  IsChecked="{TemplateBinding IsChecked}">
                        <ContentPresenter x:Name="contentPresenter" />
                    </ToggleButton>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

The test is simply whether the radio selection actually works -- so for example, the text blocks below don't show the correct value when you click on the radio buttons:

<StackPanel>
    <RadioButton x:Name="radio1" GroupName="Test" Content="1" />
    <RadioButton x:Name="radio2" GroupName="Test" Content="2" />
    <TextBlock Text="{Binding ElementName=radio1,Path=IsChecked,StringFormat='Radio 1 checked: {0}'}" />
    <TextBlock Text="{Binding ElementName=radio2,Path=IsChecked,StringFormat='Radio 2 checked: {0}'}" />
</StackPanel>

You would think that maybe there is a named part in the control template, which the control uses to update the selection -- however, the docs indicate no named parts. So what is going on here, and how can I get my example working?

War es hilfreich?

Lösung

You would think that maybe there is a named part in the control template

Yes ... it turns out there is an "undocumented feature". Trial and error shows that the "BoxMiddleLine" is the named part that controls the selection. So adding to the control template a clickable element with that name, fixes the issue:

<Grid>
    <Border x:Name="BoxMiddleLine" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="#0000" />
    <ToggleButton x:Name="toggle" 
                  IsChecked="{TemplateBinding IsChecked}"
                  IsHitTestVisible="False">
        <ContentPresenter x:Name="contentPresenter" />
    </ToggleButton>
</Grid>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top