وقتی در حال طراحی فرمی بودم که تو اون فرم چند تا Group Box مختلف استفاده کرده بودم تا دکمه رادیویی ها رو از هم جدا کنم ولی بنا به دلایلی می بایست دو تا دکمه رادیویی رو تو دوتا Group Box مختلف تو یه گروه قرار می دادم ! درسته کاره عجیبی به نظر می رسه ولی WPF با دریای قابلیت هاش این امکان رو به ما مید.
خوب بزارید اول این نحوه استفاده از این قابلیت رو بگم بعد برم سراغ Bug
وقتی بخواهیم تو XAML چند تا Option Button رو با هم در یک Group قرار دهیم خاصیت GroupName اون دکمه رادیویی رو با یک گروه که الان موجود نیست مقدار دهی می کنیم به صورت زیر:
<Grid>
<Grid.ColumnDefinitions >
<ColumnDefinition Width="150" ></ColumnDefinition>
<ColumnDefinition Width="150" ></ColumnDefinition>
</Grid.ColumnDefinitions>
<GroupBox Header="Group Box 1" Background="AliceBlue" Grid.Column=" 0" Name="Group1">
<StackPanel>
<RadioButton >Radio Button 1</RadioButton>
<RadioButton >Radio Button 2</RadioButton>
<RadioButton >Radio Button 3</RadioButton>
<RadioButton GroupName="Group3" Margin="10 5 0 0 ">Group 7</RadioButton>
</StackPanel>
</GroupBox>
<GroupBox Header="Group Box 2" Background="AntiqueWhite" Grid.Column="1" Name="Group2">
<StackPanel>
<RadioButton >Radio Button 4</RadioButton>
<RadioButton >Radio Button 5</RadioButton>
<RadioButton >Radio Button 6</RadioButton>
<RadioButton GroupName="Group3" Margin="10 5 0 0 ">Group 8</RadioButton>
</StackPanel>
</GroupBox>
</Grid>
که خروجی به صورت زیر میشه
خوب تا اینجا خیلی خوبه و این قابلیت به ما کمک می کنه ولی وقتی خصیصه IsChecked رو با True مقدار دهی می کنیم منطقا باید آخرین دکمه رادیویی که ایجاد میشه انتخاب شده باشه (در اینجا Group 8) ولی خروجی زیر رو مشاهده کنید ! 8)
سورس پایانی در هنگام وجود مشکل
<Window x:Class="test_WPF.MainForm"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="160" Width="320" Title ="WPF Crazy Bug">
<Grid>
<Grid.ColumnDefinitions >
<ColumnDefinition Width="150" ></ColumnDefinition>
<ColumnDefinition Width="150" ></ColumnDefinition>
</Grid.ColumnDefinitions>
<GroupBox Header="Group Box 1" Background="AliceBlue" Grid.Column=" 0" Name="Group1">
<StackPanel>
<RadioButton IsChecked="True" >Radio Button 1</RadioButton>
<RadioButton IsChecked="True">Radio Button 2</RadioButton>
<RadioButton >Radio Button 3</RadioButton>
<RadioButton IsChecked="True" GroupName="Group3" Margin="10 5 0 0 ">Group 7</RadioButton>
</StackPanel>
</GroupBox>
<GroupBox Header="Group Box 2" Background="AntiqueWhite" Grid.Column="1" Name="Group2">
<StackPanel>
<RadioButton >Radio Button 4</RadioButton>
<RadioButton >Radio Button 5</RadioButton>
<RadioButton >Radio Button 6</RadioButton>
<RadioButton IsChecked="True" GroupName="Group3" Margin="10 5 0 0 ">Group 8</RadioButton>
</StackPanel>
</GroupBox>
</Grid>
</Window>
دلیل این مشکل وجود Logical Tree و Visual Tree است که می توانید برای اطلاعات بیشتر به لینک زیر مراجعه کنید .
http://www.wpftutorial.net/LogicalAndVisualTree.html
منبع : Aliaghdam.blogspot.com