RadioButton を ListBox で実装する
MSDN ライブラリのバージョンに関する情報の欄に、なにげに「Microsoft Visual Studio 2010/.NET Framework 4.0」が追加されてます。
わたしが .NET Framework 4.0 に一番望むこととは、RadioButton へのデータバインドが正常に機能することですかね…。
フィードバック: RadioButton.IsCheckedProperty losing databindings
なにしろ、RadioButton の IsChecked に何かをバインディングすると、1つの対象に複数の RadioButton から同期を取ろうとするせいか、途中でバインディングが無効になってしまいます。
複数の項目から 1 つを選んで何かにバインドさせるなら、ListBox (というか Selector) が得意とするところですよね。ならば、見た目が RadioButton の ListBox を作ってやれば解決です。こういうのは WPF ならではですね。
<Window x:Class="WpfSample.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" Title="RadioButton を ListBox で実装する" SizeToContent="WidthAndHeight"> <Window.Resources> <ObjectDataProvider x:Key="Visibility" MethodName="GetValues" ObjectType="{x:Type sys:Enum}"> <ObjectDataProvider.MethodParameters> <x:Type TypeName="Visibility"/> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> </Window.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition/> </Grid.RowDefinitions> <Ellipse Fill="Orange" x:Name="TargetEllipse" Width="60" Height="60"/> <ListBox Grid.Row="1" Background="Transparent" BorderBrush="Transparent" ItemsSource="{Binding Source={StaticResource Visibility}}" SelectedValue="{Binding ElementName=TargetEllipse, Path=Visibility}"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal"/> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBox.ItemContainerStyle> <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> <RadioButton Margin="5" Content="{Binding}" IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected}" IsEnabled="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsEnabled}"/> </ControlTemplate> </Setter.Value> </Setter> </Style> </ListBox.ItemContainerStyle> </ListBox> </Grid> </Window>
トラックバック
- このエントリーにトラックバック:
- http://frog.raindrop.jp/cgi-bin/mt/mt-tb.cgi/2389
コメント
ListBox の ControlTemplate の Trigger で、IsEnabled が False の時の Background が
{DynamicResource {x:Static SystemColors.ControlBrushKey}} で決め打ちになってる。
ListBox.Style 内で Template を書き換えてあげた方がいいかも。