切换组合框(WPF)后如何在WPF中保存值

  • 本文关键字:WPF 保存 组合 c# wpf windows
  • 更新时间 :
  • 英文 :


我有two selections在我的组合框和3RadioButtons。每次切换ComboBox时,我都要保存上次的RadioButton-Selection

所以我需要以下内容:我有项目"Test1",检查了RadioButton 1。现在我切换到"Test 2"和RadioButton 1应该保存在测试1。当我切换回"Test 1"时,RadioButton 1应该被选中,因为它是"saved"之前。

希望它可以清楚我的意思。谢谢你提前帮我。

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)
{
}

可以将ComboBox中所选项目与字典中所选RadioButton之间的映射存储在一起。这段代码应该能让你明白:

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;
}
}
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;
}
}

您也可以在其他情况下使用此方法。我希望这对你有帮助!

最新更新