研究这个是出于一个群聊中碰到的一个问题:“我现在遇到个很尴尬的局面。。 我封装了一个控件 有状态A和B, 并排放置10个控件在一个Grid下面 希望点击一个控件变为A状态后 其它9个都变为状态B”,这不禁让我想起了WPF的RadioButton, 他有一个有趣的功能:“如果需要用自定义的方法对RadioButton作分组,那么可以用它的GroupName属性,这个属性是字符串类型的,任何拥有相同GroupName 的RadioButton 会被分在同个组里(只要它们在逻辑上属于同一个源)。”
那就用Reflector看看他是怎么实现的吧:
一旦RadioButton的GroupName属性发生变化,他先把自己从原始分组里面注销,然后注册到新的分组:
private static void OnGroupNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
RadioButton instance = (RadioButton) d;
string newValue = e.NewValue as string;
string str2 = _currentlyRegisteredGroupName.GetValue(instance);
if (newValue != str2)
{
if (!string.IsNullOrEmpty(str2))
{
Unregister(str2, instance);
}
if (!string.IsNullOrEmpty(newValue))
{
Register(newValue, instance);

博客探讨了WPF中RadioButton的分组行为,特别是GroupName属性如何实现分组功能。作者通过Reflector分析源码发现,GroupName变化时,RadioButton会从旧分组注销并加入新分组。静态哈希表_groupNameToElement是ThreadStatic的,但实际上只同步同一视觉树的RadioButton。当一个RadioButton状态改变,它会检查并取消同一视觉树下其他RadioButton的选择状态。此外,源码还展示了注册、注销和处理已销毁RadioButton的细节。
最低0.47元/天 解锁文章
1617

被折叠的 条评论
为什么被折叠?



