0

我有一个组合框

<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。但这不是我想要的。

4

1 回答 1

1

所以,我想我知道这里发生了什么。您已经填充了您的ComboBoxwithComboBoxItems并且稍后尝试将其设置SelectedValuestring. 当您这样做时,ComboBox检查它是否包含该新值。它用于ComboBoxItem.Equals()执行此检查,检查引用是否相等。显然,此检查将始终返回false,因为被比较的两个对象的类型不同,这就是为什么ComboBox无法找到它并因此显示它的原因。正确的做法是将ComboBox'sItemsSource设置为强类型的字符串集合。如果你这样做,ComboBoxString.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>。不过,这可能是另一天的练习!

于 2013-05-03T20:42:01.390 回答