2014-03-31 50 views
2

我有一個單選按鈕組:WPF綁定到選定的單選按鈕

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

如何綁定標籤到選定的單選按鈕的內容內容?

例如標籤應該說創建圖表或創建地圖取決於哪個單選框被創建?

+0

您可以將RB放入listBox(並將IsChecked綁定到Item.IsSelected)並將標籤綁定到selecteditem \ value。 – dovid

+1

@lomed,顯示我的代碼,我接受你的答案。但我不想改變收音機的外觀 – GreyCloud

回答

2
<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> 

我想你可以把它比我做短。

+0

由於某種原因,我不能取消收音機框,我也可以選擇他們兩個?我認爲這個解決方案需要一個值轉換器,因爲我看不到標籤更改值? – GreyCloud

+2

您可以選擇兩個RadioButton,因爲它們不在組中。在上面的代碼中將'GroupName =「MapOrGraph」'添加到RadioButton中,它應該可以工作。 – phil

+0

@GreyCloud我編輯過,請重試。 – dovid

1

如果你只有兩個單選按鈕,這是一個快速&骯髒的解決方案:

<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> 
+0

這個想法很好,但我似乎無法得到這個工作: -/ – GreyCloud

+0

我已經更新了答案。只需複製XAML中的標籤並檢查名稱(_CreateGraph,_CreateMap)。這應該工作。 – phil

+0

完美,謝謝:) – GreyCloud