I have two selections
in my ComboBox and 3 RadioButtons
. And I want to save my last RadioButton
-Selection every time I switch my ComboBox
.
So I need following:
I have Item "Test1"
and checked RadioButton 1
. Now I switch to "Test 2"
and RadioButton 1 should be saved at Test 1. When I switch back to "Test 1"
RadioButton 1
should be checked, because it was "saved" before.
Hopefully it's clear what I meant. Thanks for helping me out in advance.
MainWindow.xaml
<RadioButton x:Name="RBTN1" GroupName="Test" Content="Test1"/>
<RadioButton x:Name="RBTN2" GroupName="Test" Content="Test2"/>
<RadioButton x:Name="RBTN3" GroupName="Test" Content="Test3"/>
<ComboBox x:Name="CMBBX" SelectionChanged="CMBBX_SelectionChanged" />
MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
CMBBX.Items.Add("Test 1");
CMBBX.Items.Add("Test 2");
}
private void CMBBX_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
CodePudding user response:
private void CMBBX_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (CMBBX.SelectedIndex == 0)
{
RBTN1.IsChecked = true;
RBTN2.IsChecked = false;
RBTN3.IsChecked = false;
}
else if (CMBBX.SelectedIndex == 1)
{
RBTN1.IsChecked = false;
RBTN2.IsChecked = true;
RBTN3.IsChecked = false;
}
}
You can use this method for other situations too. I hope it'll be helpful for you!
CodePudding user response:
You could store the mappings between the selected item in the ComboBox
and the selected RadioButton
in a dictionary. This code should give you the idea:
public partial class MainWindow : Window
{
private readonly Dictionary<string, RadioButton> _items = new Dictionary<string, RadioButton>();
private string _selectedItem;
public MainWindow()
{
InitializeComponent();
_items.Add("Test 1", null);
_items.Add("Test 2", null);
CMBBX.ItemsSource = _items.Keys;
}
private void CMBBX_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// save
if (_selectedItem != null)
_items[_selectedItem] = GetSelectedRadioButton();
_selectedItem = CMBBX.SelectedItem as string;
// restore
if (_selectedItem != null
&& _items.TryGetValue(_selectedItem, out RadioButton radioButton)
&& radioButton != null)
radioButton.IsChecked = true;
}
private RadioButton GetSelectedRadioButton()
{
if (RBTN1.IsChecked == true)
return RBTN1;
if (RBTN2.IsChecked == true)
return RBTN2;
if (RBTN3.IsChecked == true)
return RBTN3;
return null;
}
}