2017-09-19 58 views
0

所以我试图完成这样的事情的启动检索此: 例如在Windows 10中的标准消息应用程序,我可以选择一个项目: enter image description here保存组合框选择在应用

所以当我重新启动应用程序的选择将仍然是相同的: enter image description here

所以我想完成相同的事情,甚至保存选定的项目作为一个字符串。所以我可能需要2个localsettings一个用于selecteditem,另一个用于将所选项目的内容保存为字符串。

这是我想出了,但这不起作用(XAML):

<ComboBox Name="Preference" SelectionChanged="ComboBox_SelectionChanged"> 
    <ComboBoxItem Content="Diving"/> 
    <ComboBoxItem Content="Snorkeling"/> 
    <ComboBoxItem Content="Diving and Snorkeling"/> 
</ComboBox> 

(CS)

public Settings() 
{ 
    this.InitializeComponent(); 

    Preference.SelectedItem = App.localSettings.Values["Preference"]; 
} 

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    App.localSettings.Values["Preference"] = Preference.SelectedItem; 
} 

我还在努力学习C#,所以请保持简单。我尝试搜索它,但没有真正找到回答我的问题的东西。

+0

检查https://stackoverflow.com/questions/845030/bind-to-设置中的a值定义可将属性直接绑定到设置。 – Fruchtzwerg

+0

和另一种方式。您可以将其保存到txt文件中,以便每当应用程序启动或初始化txt文件从存储中自动将其设置为上次保存状态的任何页面时 –

回答

2

SelectedItem需要是ComboBox包含的实际项目。你用ComboBoxItems填充ComboBox,所以你的SelectedItem需要是一个ComboBoxItem。

有两种方法可以解决这个问题。首先是将SelectedItem设置为与您的字符串具有相同内容的CombobBoxItem。第二个是用字符串填充ComboBox。

一个(只对代码变化)

string preference = PreferenceApp.localSettings.Values["Preference"]; 
Preference.SelectedItem = Preference.Items.OfType<ComboBoxItem>().FirstOrDefault(item => item.Content == preference); 

两个(XAML只改变)

<ComboBox Name="Preference" SelectionChanged="ComboBox_SelectionChanged"> 
    <x:String>Diving</x:String> 
    <x:String>Snorkeling</x:String> 
    <x:String>Diving and Snorkeling</x:String> 
</ComboBox>