[英]Load Selected item of combobox from roaming settings
我有一個組合框
<ComboBox x:Name="cityPicker">
<ComboBoxItem IsSelected="True">
<x:String>
city1
</x:String>
</ComboBoxItem>
<ComboBoxItem>
<x:String>
city2
</x:String>
</ComboBoxItem>
當用戶選擇“ city2”時,我將其保存到selectedCity
鍵中的漫游設置中。
當用戶退出后啟動應用程序並從另一個頁面返回此頁面時,我需要從漫游設置中加載此值。
將此代碼值保存到RoamingSetting,並且在更改城市后啟動應用程序時,roamingsettings具有其值。 但是Combobox不會檢索它。 組合框所選項目保持為空。
如何以編程方式更改組合框中的所選項目?
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
if (roamingSettings.Values.ContainsKey("selectedCity"))
{
cityPicker.SelectedValue = roamingSettings.Values["selectedCity"].ToString();
}
}
public StartPage()
{
InitializeComponent();
cityPicker.SelectionChanged += cityPicker_SelectionChanged;
}
void cityPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var roamingSettings =
Windows.Storage.ApplicationData.Current.RoamingSettings;
var cityPick = cityPicker.SelectedItem as ComboBoxItem;
if (cityPick != null) roamingSettings.Values["selectedCity"] = cityPick.Content;
}
我只能通過更改SelectedIndex
來做到。 但這不是我想要的。
所以,我想我知道這里發生了什么。 你已經填充了ComboBox
與ComboBoxItems
和稍后嘗試其設置SelectedValue
到一個string
。 當您這樣做時, ComboBox
檢查它是否包含該新值。 它使用ComboBoxItem.Equals()
執行此檢查,該檢查檢查引用是否相等。 顯然,此檢查將始終返回false
因為要比較的兩個對象的類型不同,這就是ComboBox
無法找到並顯示它的原因。 正確的做法是將ComboBox
的ItemsSource
設置為強類型的字符串集合。 如果這樣做,則ComboBox
將使用String.Equals()
進行相等性檢查,該檢查使用值類型相等語義執行相等性。
假設您有一個ComboBox
,其name
設置為“ comboBox”。 在您的代碼隱藏事件處理程序處理程序中:
IEnumerable<string> foo = new[] { "A", "B", "C" };
comboBox.ItemsSource = foo;
comboBox.SelectedValue = "B"; // This should work
這是一個與您的代碼直接相關的示例
XAML:
<ComboBox x:Name="cityPicker" />
C#:
public StartPage()
{
InitializeComponent();
cityPicker.ItemsSource = new[] { "city1", "city2" };
cityPicker.SelectionChanged += OnCityPickerSelectionChanged;
}
void OnCityPickerSelectionChanged(object sender, SelectionChangedEventArgs e)
{
// get your roaming settings
var selectedItem = cityPicker.SelectedItem;
roamingSettings.Values["SelectedCity"] = (string) selectedItem;
}
protected override void LoadState(...)
{
// get roaming settings, perform key check
cityPicker.SelectedValue = (string) (roamingSettings.Values["SelectedCity"]);
}
顯然,做到這一點的“正確”方法是擁有一個暴露ObservableCollection<string>
的視圖模型。 您可以將此視圖模型設置為數據上下文,然后在ItemsSource
和視圖模型ObservableCollection<string>
之間建立綁定。 不過,這可能是另一天的練習!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.