将ComboBox项绑定到radiobuttons列表wpf的属性

时间:2017-07-04 11:36:55

标签: c# wpf mvvm combobox binding

我有ComboBox我希望绑定到ObservableCollection<RadioButton>。不过,我希望列出ToolTip中的ComboBox属性,而不是实际的RadioButtons

示例:

如果我有3 RadioButtons ToolTips 1,2和3.我希望ComboBox包含3个字符串项,1,2和3。

代码:

查看:

<ComboBox x:Name="LandmarkIdComboBox" Grid.Column="1" DisplayMemberPath="ToolTip" ItemsSource="{Binding Landmarks, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
          SelectedItem="{Binding SelectedLandmark, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalContentAlignment="Center" HorizontalAlignment="Stretch"
          VerticalAlignment="Center" VerticalContentAlignment="Center"/>

视图模型:

private ObservableCollection<RadioButton> m_landmarks = new ObservableCollection<RadioButton>();
private RadioButton m_selectedLandmark;

public ObservableCollection<RadioButton> Landmarks
{
    get => m_landmarks;
    set
    {
        m_landmarks = value;
        OnPropertyChanged();
    }
}
public RadioButton SelectedLandmark
{
    get => m_selectedLandmark;
    set
    {
        m_selectedLandmark = value;
        OnPropertyChanged();
    }
}

使用上面的代码,我可以看到提到的1,2和3项,但我无法选择它们。我猜是因为它们不是常规项目而是RadioButtons所以点击它们会使它们成为Checked / UnChecked而不是选中。

我可以使用额外的Strruct/Class来实现我的需要,但当然我不愿意,如果有另一种方式。

那么,还有另一种方式吗?

1 个答案:

答案 0 :(得分:1)

这不是选择问题,而是RadioButtonContentControl的事实。这意味着在Content中选择时会显示ComboBox

您可以通过定义自定义ControlTemplate

来解决此问题
<ComboBox x:Name="LandmarkIdComboBox" Grid.Column="1" ItemsSource="{Binding Landmarks}" SelectedItem="{Binding SelectedLandmark}"
          HorizontalContentAlignment="Center" HorizontalAlignment="Stretch"
          VerticalAlignment="Center" VerticalContentAlignment="Center">
    <ComboBox.Resources>
        <Style TargetType="RadioButton">
            <Setter Property="Content" Value="{Binding ToolTip, RelativeSource={RelativeSource Self}}" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="RadioButton">
                        <TextBlock Text="{TemplateBinding ToolTip}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ComboBox.Resources>
</ComboBox>

在视图模型中定义ObservableCollection<RadioButton>会破坏MVVM模式,但我想你有理由。

相关问题