Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: RadioButton IsChecked displayed incorrectly when switching ViewModel. #17765

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions src/Avalonia.Controls/RadioButton.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,21 @@ private void OnGroupNameChanged(string? oldGroupName, string? newGroupName)
if (value.GetValueOrDefault())
{
EnsureRadioGroupManager();
_groupManager.OnCheckedChanged(this);
_groupManager?.OnCheckedChanged(this);
}
}

[MemberNotNull(nameof(_groupManager))]
private void EnsureRadioGroupManager(IRenderRoot? root = null)
{
_groupManager = RadioButtonGroupManager.GetOrCreateForRoot(root ?? this.GetVisualRoot());
root = root ?? this.GetVisualRoot();

if (root == null)
{
return;
}

_groupManager = RadioButtonGroupManager.GetOrCreateForRoot(root);

_groupManager.Add(this);
}
}
Expand Down
18 changes: 14 additions & 4 deletions src/Avalonia.Controls/RadioButtonGroupManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,13 @@ internal interface IRadioButton : ILogical

internal class RadioButtonGroupManager
{
private static readonly RadioButtonGroupManager s_default = new();
private static readonly ConditionalWeakTable<IRenderRoot, RadioButtonGroupManager> s_registeredVisualRoots = new();

private readonly Dictionary<string, List<WeakReference<IRadioButton>>> _registeredGroups = new();
private bool _ignoreCheckedChanges;

public static RadioButtonGroupManager GetOrCreateForRoot(IRenderRoot? root)
public static RadioButtonGroupManager GetOrCreateForRoot(IRenderRoot root)
{
if (root == null)
return s_default;
return s_registeredVisualRoots.GetValue(root, key => new RadioButtonGroupManager());
}

Expand All @@ -41,6 +38,19 @@ public void Add(IRadioButton radioButton)
_registeredGroups.Add(groupName, group);
}

foreach(var item in group)
{
if (!item.TryGetTarget(out var button))
{
continue;
}

//Return if the button is already in the group
if (button == radioButton)
{
return;
}
}
group.Add(new WeakReference<IRadioButton>(radioButton));
}
}
Expand Down
Loading