Связывание выбранного элемента списка элементов с переключателями в выпадающем списке - PullRequest
2 голосов
/ 07 сентября 2011

Хорошо, так что мой вопрос немного запутан, поэтому я постараюсь быть максимально ясным. Поскольку у коллекции переключателей нет свойства SelectedItem / Value, я собрал свои radioButtons в ListBox на основе некоторого XAML, который я нашел в сети. Теперь, чтобы сэкономить место в пользовательском интерфейсе, этот ListBox принимает содержимое всплывающего окна ComboBox. (Поэтому, когда вы нажимаете comboBox, выпадающий список представляет собой список радиокнопок в WrapPanel.) Я смог успешно привязать элемент управления списка RadioButton сам по себе к элементу источника и привязать выбранное значение к свойству, но один раз внутри комбо Я не могу заставить привязку выбранного значения работать должным образом (ItemsSource по-прежнему работает нормально).

<Style x:Key="RadioButtonList" TargetType="{x:Type ListBox}">
    <Setter Property="Background" Value="White"/>
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <WrapPanel Background="Transparent" />
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="{x:Type ListBoxItem}" >
                <Setter Property="Margin" Value="5" />
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type ListBoxItem}">
                            <Border BorderThickness="1" Background="Transparent">
                                <RadioButton Focusable="False" Width="120"
                                        IsHitTestVisible="False"
                                        Content="{Binding Name}"
                                        IsChecked="{TemplateBinding IsSelected}">
                                </RadioButton>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Setter.Value>
    </Setter>
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBox}">
                <Border BorderThickness="0" Padding="0" BorderBrush="Transparent" Background="Transparent" Name="Bd" SnapsToDevicePixels="True">
                    <ItemsPresenter SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<Style x:Key="RadioButtonCombo" TargetType="ComboBox">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ComboBox">
                <Grid>
                    <ToggleButton 
                            Name="ToggleButton"
                            DataContext="{TemplateBinding ItemsSource}"
                            Content="{Binding ElementName=DropDownContent, Path=SelectedItem.Name}"
                            Focusable="false"
                            IsChecked="{Binding Path=IsDropDownOpen,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}"
                            ClickMode="Press" />
                    <ContentPresenter
                            Name="ContentSite"
                            IsHitTestVisible="False" 

                            ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
                            ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"
                            Margin="3,3,23,3"
                            VerticalAlignment="Center"
                            HorizontalAlignment="Left" />
                    <Popup Name="Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}"
                            AllowsTransparency="True" Focusable="False" PopupAnimation="Slide">
                        <Grid Name="DropDown" SnapsToDevicePixels="True"
                              MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}">
                            <Border x:Name="DropDownBorder" Background="WhiteSmoke"
                                    BorderThickness="1" BorderBrush="Black"/>
                            <ListBox Name="DropDownContent" Style="{StaticResource RadioButtonList}" 
                                     Width="{TemplateBinding MaxWidth}"
                                     SelectedValue="{Binding Path=SelectedValue, RelativeSource={RelativeSource TemplatedParent}}"
                                     ItemsSource="{TemplateBinding ItemsSource}">
                            </ListBox>
                        </Grid>
                    </Popup>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
    </Style.Triggers>
</Style>

Мое использование выглядит следующим образом:

    <ComboBox Name="SourceComboCtl" 
              Text="Source" 
              SelectedValuePath="CodeId" 
              DisplayMemberPath="Name" 
              SelectedValue="{Binding Path=SourceCode}"
              Style="{StaticResource RadioButtonCombo}"
              Width="60" 
              MaxWidth="150" />

1 Ответ

2 голосов
/ 07 сентября 2011

Я немного сбит с толку, почему вы сначала перезаписываете ListBox для отображения RadioButtons, а затем перезаписываете ComboBox для использования ListBox для отображения RadioButtons

Почему бы просто не переписать ComboBox.ItemTemplate и вообще не пропускать ListBox? ComboBox имеет SelectedItem / Value тоже

Вот мой стиль RadioButtonListBox. Я просто изменил, где написано ListBox, чтобы сказать ComboBox

<Style x:Key="RadioButtonComboBoxStyle" TargetType="{x:Type ComboBox}">
    <Setter Property="BorderBrush" Value="Transparent"/>
    <Setter Property="KeyboardNavigation.DirectionalNavigation" Value="Cycle" />
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="{x:Type ComboBoxItem}" >
                <Setter Property="Margin" Value="2, 2, 2, 0" />
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <Border Background="Transparent">
                                <RadioButton IsHitTestVisible="False" Focusable="false" 
                                    Content="{TemplateBinding ContentPresenter.Content}"  
                                    IsChecked="{Binding Path=IsSelected,RelativeSource={RelativeSource TemplatedParent},Mode=TwoWay}"/>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Setter.Value>
    </Setter>
</Style>
...