0

再利用可能なUserControlを使用すると、RadioButtonに問題が発生します。何らかの理由で、各「Chooser」コントロールのラジオボタンをチェックできませんが、代わりに1つのラジオボタンをチェックすると、現在のチューザーと他のチューザーの他のすべてのラジオボタンがオフになります。各「chooser」ユーザーコントロールにチェック項目を含めることができるように、このコードを変更する方法を知っている人はいますか。ユーザーコントロールは、コレクションを使用して動的に構築できる必要があります。実際の例では、「chooser」ユーザーコントロールごとに異なるテキスト値があります。

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"
                                    };
    }
}
4

1 に答える 1

1

グループ化を指示するには、RadioButtonのGroupNameプロパティを使用する必要があることがわかりました。これを行うには、アイテムソースを文字列型の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; }
}

これが誰かを助けることを願っています。

于 2012-12-17T00:10:59.620 に答える