使用可重复使用的UserControl时,我遇到了RadioButton的问题。出于某种原因,我无法检查每个“选配器”控件的单选按钮,但是当选中一个单选按钮时,当前选择器和其他选择器中的所有其他单选按钮都将被取消选中。有谁知道如何更改此代码,以便我可以在每个'选择器'用户控件中有一个选中的项目。必须能够使用集合动态构建用户控件。在现实世界的示例中,每个“选择器”用户控件将具有不同的文本值。
MainPage.xaml中
<StackPanel x:Name="LayoutRoot" Background="White">
<radioButtonTest:Chooser />
<radioButtonTest:Chooser />
<radioButtonTest:Chooser />
</StackPanel>
Chooser.xaml
<UserControl x:Class="RadioButtonTest.Chooser"
xmlns ...>
<StackPanel x:Name="LayoutRoot" Orientation="Horizontal">
<TextBlock x:Name="MyLabel" Text="Choices:" VerticalAlignment="Center" Margin="0,0,10,0" />
<ItemsControl x:Name="MyChooser" Height="25" VerticalAlignment="Top" HorizontalAlignment="Left">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton Height="22" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Content="{Binding}" MinWidth="35" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</UserControl>
Chooser.xaml.cs
public partial class Chooser
{
public Chooser()
{
InitializeComponent();
// adding some test items to the itemscontrol
MyChooser.ItemsSource = new ObservableCollection<string>
{
"first",
"second",
"third"
};
}
}
答案 0 :(得分:1)
原来我需要使用RadioButton的GroupName属性来指定分组。我这样做是通过将项源更改为具有string类型的Group属性的自定义类,并将此属性绑定到RadioButton上的GroupName属性。
XAML:
<DataTemplate>
<RadioButton ... Content="{Binding Name}" GroupName="{Binding Group}" />
</DataTemplate>
C#:
public Chooser()
{
InitializeComponent();
// the groupName needs to be the same for each item
// in the radio group, but unique for each separate group.
var groupName = Guid.NewGuid().ToString();
MyChooser.ItemsSource = new ObservableCollection<RadioButtonGroupItem>
{
new RadioButtonGroupItem {Group = groupName, Name = "first"},
new RadioButtonGroupItem {Group = groupName, Name = "second"},
new RadioButtonGroupItem {Group = groupName, Name = "third"}
};
}
public class RadioButtonGroupItem
{
public string Name { get; set; }
public string Group { get; set; }
}
希望这有助于某人。