WPF自定義控制元件中使用了RadioButton後,多次使用該控制元件出現的死迴圈解決方法
阿新 • • 發佈:2018-12-31
最近在專案中需要用到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;
問題基本上解決了。