gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:09:38 25 4
gpt4 key购买 nike

我将同一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com