tags:

views:

554

answers:

1

I have a menu in my WPF application with multiple options which act like radio button group (selecting one deselects rest of them) and I'd like to use checkable menu items as templates for radio buttons.

I've tried to set the template but it doesn't seem to work like one would expect. Selecting and unselecting items do not seem to be synchronized with radio buttons' values.

I guess I could use more complex template and "fake" the selected mark using Path or something but it seems awfully lot of work for such a simple purpose. Also when using more complex template I'd have to address different themes which I'd rather not want to do.

Here's a simple example to demonstrate the problem.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;  
  <Page.Resources>
    <ControlTemplate x:Key="Template" TargetType="{x:Type RadioButton}">      
      <MenuItem x:Name="item" Header="{TemplateBinding Content}" IsCheckable="True" IsChecked="False" />

      <ControlTemplate.Triggers>
        <Trigger Property="IsChecked" Value="True">
          <Setter TargetName="item" Property="IsChecked" Value="True" />
        </Trigger>
      </ControlTemplate.Triggers>      
    </ControlTemplate>
  </Page.Resources> 

  <StackPanel>
    <RadioButton Content="Foo" Template="{StaticResource Template}"/>  
    <RadioButton Content="Bar" Template="{StaticResource Template}"/>  
    <RadioButton Content="Biz" Template="{StaticResource Template}"/>  
  </StackPanel>  
</Page>
+2  A: 

The problem seemed to be that the MenuItem's mouse event handlers were taking over for the RadioButton. When I set IsHitTestVisible on the MenuItem to false and added a Border to soak up mouse events, it seemed to work as you expect:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;
    <Page.Resources>
        <ControlTemplate x:Key="Template" TargetType="{x:Type RadioButton}">
            <Border Background="Transparent">
                <MenuItem Header="{TemplateBinding Content}" IsCheckable="False" IsChecked="{TemplateBinding IsChecked}" IsHitTestVisible="False"/>
            </Border>
        </ControlTemplate>
    </Page.Resources>
    <StackPanel>
        <RadioButton Content="Foo" IsChecked="True" Template="{StaticResource Template}"/>
        <RadioButton Content="Bar" Template="{StaticResource Template}"/>
        <RadioButton Content="Biz" Template="{StaticResource Template}"/>
    </StackPanel>
</Page>
Robert Macnee