c# - WPF 单选按钮组与自定义用户控件发生冲突

标签 c# wpf xaml radio-button

我将同一个 UserControl 实例化了两次。两者都有单选按钮并共享 GroupName。当我选择一个时,所有其他人都取消选择,即使它们属于不同的 UserControl 实例。

如何避免这种 GroupName 冲突?

下面是一个简单的例子来说明这一点:

主xaml

<Window x:Class="RadioDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <UserControl x:Name="First"/>
        <UserControl x:Name="Second"/>
    </StackPanel>
</Window>

主要代码隐藏

public MainWindow()
{
    InitializeComponent();
    Loaded += MainWindow_Loaded;
}

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    First.Content = new MyRadio();
    Second.Content = new MyRadio();
}

MyRadio xaml

<UserControl x:Class="RadioDemo.MyRadio"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <StackPanel>
        <RadioButton GroupName="G" x:Name="RadioOne" Content="RadioOne"/>
        <RadioButton GroupName="G" x:Name="RadioTwo" Content="RadioTwo"/>
    </StackPanel>
</UserControl>

最佳答案

加载用户控件后,您可以动态创建组名称值。

XAML:

<StackPanel>
    <RadioButton GroupName="{Binding GroupNameValue}" x:Name="RadioOne" Content="RadioOne"/>
    <RadioButton GroupName="{Binding GroupNameValue}" x:Name="RadioTwo" Content="RadioTwo"/>
</StackPanel>

View 模型:

private string groupNameValue = Guid.NewGuid().ToString();

public string GroupNameValue
{
    protected get { return this.groupNameValue; }
    set
    {
        this.SetProperty(ref this.groupNameValue, value);
    }
}

SetPropertyINotifyPropertyChanged 的实现。
这里我用了Guid作为唯一性的保证,但您可以随意使用。

使用 C# 6.0 可以简化代码:

private string groupNameValue = Guid.NewGuid().ToString();

public string GroupNameValue => this.groupNameValue;

关于c# - WPF 单选按钮组与自定义用户控件发生冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38563541/

相关文章:

wpf - 如何防止跳转到 UserControl?

c# - 执行 RenderTargetBitmap 后 Viewport3D 不更新视觉效果

c# - 使游戏对象在编辑器窗口中不可选择

c# - WPF 如何管理 ENTER 命中 TextBox 以进行消息传递

wpf - 我如何在 XAML 中执行此操作?

c# - 通过拇指调整用户控件的 wpf 大小与拖动不成比例

c# - 使用哪种对象集合类型?

c# - WPF C# 长时间运行操作

c# - Xamarin ContentView/View 生命周期

c# - 如何在 WPF/XAML 中反射(reflect)类的继承?