WPF自定义控件中使用了RadioButton后,多次使用该控件出现的死循环解决方法

最近在项目中需要用到RadioButton,所以在自定义控件中使用了一组RadioButton,使用一个默认的groupname,也就是这个goupname给后来的问题埋下了地雷。

定义大致如下:

<Grid>
        <Label Height ="50" Width="100" Content="{Binding Title,ElementName=PointInput,Path=Title,Mode=TwoWay}"></Label>
        <RadioButton GroupName="radiobutton" IsChecked ="{Binding Checked}"></RadioButton>
        <RadioButton GroupName="radiobutton" IsChecked ="{Binding Checked,Converter={StaticResource notBooleanConvert},ConverterParameter=True}"></RadioButton>
    </Grid>

在使用这个自定义控件的时候,如果只使用一个没有问题,如果多个一起使用的时候,就会出现死循环的问题。后来发现可能多个自定义控件中RadioButton使用了同一个groupname,造成了数据混乱。既然找到了问题,解决起来也很简单了。

首先给自定义的中的两个RaioButton定义不同的name。

<Grid>
        <Label Height ="50" Width="100" Content="{Binding Title,ElementName=PointInput,Path=Title,Mode=TwoWay}"></Label>
        <RadioButton Name="radiobutton1"  IsChecked ="{Binding Checked}"></RadioButton>
        <RadioButton Name="radiobutton2" IsChecked ="{Binding Checked,Converter={StaticResource notBooleanConvert},ConverterParameter=True}"></RadioButton>
    </Grid>

然后在自定义控件的构造函数中给这两个RadioButton赋值一个随机的名字,我的做法是采用uuid。 

string uuid = Guid.NewGuid().ToString(); 
radiobutton1.GroupName = uuid;
radiobutton2.GroupName = uuid;

问题基本上解决了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值