Windows Phone 8.1 ApplicationData 本地数据存储 键值对

network | | 访问(69)
<StackPanel>
    <StackPanel Orientation="Horizontal">
        <TextBlock x:Name="textBlock1" Text="Key:" Width="150" />
        <TextBox x:Name="txtKey" Text="" Width="200" />
    </StackPanel>
    <StackPanel Orientation="Horizontal" Margin="0 20 0 0">
        <TextBlock  Text="Value:" Width="150" />
        <TextBox x:Name="txtValue" Text="" Width="200" />
    </StackPanel>
    <Button Content="保存" x:Name="btnSave" Click="btnSave_Click" />
    <Button Content="删除" x:Name="btnDelete"  Click="btnDelete_Click" />
    <Button Content="清空所有" x:Name="deleteall" Click="deleteall_Click" />
    <TextBlock Text="Keys列表:"/>
    <ListBox Height="168"  x:Name="lstKeys" SelectionChanged="lstKeys_SelectionChanged" />
</StackPanel>
public sealed partial class MainPage: Page {
    private ApplicationDataContainer _appSettings;
    public MainPage() {
        InitializeComponent();
        _appSettings = ApplicationData.Current.LocalSettings;
        BindKeyList();
    }

    private async void btnSave_Click(object sender, RoutedEventArgs e) {
        if (!String.IsNullOrEmpty(txtKey.Text)) {
            _appSettings.Values[txtKey.Text] = txtValue.Text;
            BindKeyList();
        } else {
            await new MessageDialog("请输入key值").ShowAsync();
        }
    }

    private void btnDelete_Click(object sender, RoutedEventArgs e) {
        if (lstKeys.SelectedIndex > -1) {
            _appSettings.Values.Remove(lstKeys.SelectedItem.ToString());
            BindKeyList();
        }
    }

    private void lstKeys_SelectionChanged(object sender, SelectionChangedEventArgs e) {
        if (e.AddedItems.Count > 0) {
            string key = e.AddedItems[0].ToString();
            if (_appSettings.Values.ContainsKey(key)) {
                txtKey.Text = key;
                txtValue.Text = _appSettings.Values[key].ToString();
            }
        }
    }

    private void BindKeyList() {
        lstKeys.Items.Clear();
        foreach(string key in _appSettings.Values.Keys) {
            lstKeys.Items.Add(key);
        }
        txtKey.Text = "";
        txtValue.Text = "";
    }
    private void deleteall_Click(object sender, RoutedEventArgs e) {
        _appSettings.Values.Clear();
        BindKeyList();
    }
}