我需要保存在运行时由用户更改的组合框值,并在下次加载页面时将其显示为组合框默认值。我问这是我的UWP申请。我在Settings.xaml中定义了一个组合框,如下所示:
<ComboBox Name="CLengthCombo" SelectionChanged="ComboBox_SelectionChanged">
<ComboBoxItem Content="24"/>
<ComboBoxItem Content="25"/>
<ComboBoxItem Content="26" IsSelected="True"/>
<ComboBoxItem Content="27"/>
</ComboBox>
在我的Settings.xaml.cs中,我定义了一个名为&#34; localSettings_CycleLength&#34;的全局变量。为了保存更改的组合框值,使其保持在应用程序启动之间:
Windows.Storage.ApplicationDataContainer localSettings_CycleLength = Windows.Storage.ApplicationData.Current.LocalSettings;
然后我在Settings.xaml.cs中有以下代码:
public Settings()
{
this.InitializeComponent();
if (localSettings_CycleLength.Values["CycleLength"] != null)
{
this.CLengthCombo.SelectedItem = localSettings_CycleLength.Values["CycleLength"];
}
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var comboBoxItem = e.AddedItems[0] as ComboBoxItem;
if (comboBoxItem == null) return;
comboBoxItem.IsSelected = true;
var content = comboBoxItem.Content as string;
if (content != null)
{
localSettings_CycleLength.Values["CycleLength"] = content;
}
}
现在,上面的代码没有做我需要的,我也不知道为什么。你能帮帮我吗?先谢谢你!
答案 0 :(得分:2)
您正在存储所选ComboBoxItem
的内容。因此,您无法将内容分配给SelectedItem
你应该这样做
if (localSettings_CycleLength.Values.ContainsKey("CycleLength"))
{
var savedItem = localSettings_CycleLength.Values["CycleLength"]; ;
foreach(var item in CLengthCombo.Items)
{
if((item as ComboBoxItem).Content.Equals(savedItem ))
{
this.CLengthCombo.SelectedItem = item;
}
}
}
你的xaml中有<ComboBoxItem Content="26" IsSelected="True"/>
。所以每次加载页面时都会选择26覆盖之前选择的项目