【问题标题】:WPF Bind to selected Radio ButtonWPF 绑定到选定的单选按钮
【发布时间】:2014-03-31 13:22:40
【问题描述】:

我有一个 Radiobutton 组:

 <RadioButton Name="_CreateGraph" GroupName="MapOrGraph" Content="Create Graph" />
 <RadioButton Name="_CreateMap"   GroupName="MapOrGraph" Content="Create Map"   />

如何将标签的内容绑定到所选单选按钮的内容?

例如标签应该是 Create Graph 还是 Create Map,具体取决于创建的单选框?

【问题讨论】:

  • 您可以将RB放在listBox中(并将IsChecked绑定到Item.IsSelected)并将标签绑定到selecteditem\value。
  • @lomed,给我看代码,我接受你的回答。但是我不想改变单选框的外观和感觉

标签: c# wpf


【解决方案1】:
<Label Content="{Binding SelectedValue.Content, ElementName=list}"  />

<ListBox x:Name="list" SelectedIndex="1"  >
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem" >
                        <RadioButton GroupName="a" Content="{TemplateBinding Content}" IsChecked="{Binding IsSelected, RelativeSource={RelativeSource TemplatedParent}  }"  />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBoxItem>Create Graph</ListBoxItem>
    <ListBoxItem>Create Map</ListBoxItem>
</ListBox>

我认为你可以让它比我做的更短。

【讨论】:

  • 由于某种原因我无法取消设置单选框,我也可以同时选择它们?我还认为这个解决方案需要一个值转换器,因为我看不到标签改变值?
  • 您可以同时选择两个 RadioButton,因为它们不在组中。将GroupName="MapOrGraph" 添加到上面代码中的 RadioButton 中,它应该可以工作。
【解决方案2】:

如果您只有两个 RadioButtons,这是一个快速而肮脏的解决方案:

    <Label>
        <Label.Style>
            <Style TargetType="{x:Type Label}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsChecked, ElementName=_CreateGraph}" Value="True">
                        <Setter Property="Content" Value="{Binding Content, ElementName=_CreateGraph}" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding IsChecked, ElementName=_CreateMap}" Value="True">
                        <Setter Property="Content" Value="{Binding Content, ElementName=_CreateMap}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Label.Style>
    </Label>

【讨论】:

  • 我已经更新了答案。只需复制 XAML 中的标签并检查名称(_CreateGraph、_CreateMap)。这应该有效。
猜你喜欢
  • 1970-01-01
  • 2010-11-22
  • 1970-01-01
  • 2011-10-06
  • 2014-06-19
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 2014-02-03
相关资源
最近更新 更多