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;

问题基本上解决了。

猜你喜欢

转载自blog.csdn.net/woddle/article/details/84339770