2017-09-19 63 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>