简体   繁体   English

使用类绑定设置(Windows Phone)

[英]Using a class to bind settings (Windows Phone)

I'm new to WP development and I have a problem I can't get fixed on my own. 我是WP开发的新手,但有一个我无法自行解决的问题。 I'm trying to set up a settings page. 我正在尝试设置一个设置页面。 I copied most of it from that msdn article: 我从msdn文章中复制了大部分内容:

http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769510(v=vs.105).aspx#BKMK_CreatingaSettingsPageThatDoesNotRequireaConfirmationButton http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769510(v=vs.105).aspx#BKMK_CreatingaSettingsPageThatDoesNotRequireaConfirmationButton

The problem is connected to this line: 问题连接到这条线:

<phone:PhoneApplicationPage.Resources>
  <local:Page1 x:Key="appSettings" />
</phone:PhoneApplicationPage.Resources>

It behaves completly random. 它的行为完全是随机的。 Most of the time VS just crashes. 大多数情况下,VS只是崩溃。 I am sure that this is because VS tries to connect to the IsolatedStorage. 我确定这是因为VS尝试连接到IsolatedStorage。 But the Emulator just closes the App when I try to access the page. 但是,当我尝试访问该页面时,仿真器只是关闭了该应用程序。

The full code of the settings page (Page1): 设置页面(Page1)的完整代码:
Page1.xaml: 的Page1.xaml:

    <phone:PhoneApplicationPage 
    x:Class="MyApp.Page1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    xmlns:local="clr-namespace:MyApp"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True">

    <phone:PhoneApplicationPage.Resources>
      <local:Page1 x:Key="appSettings" />
    </phone:PhoneApplicationPage.Resources>


        <!--LayoutRoot is the root grid where all page content is placed-->

        <Grid x:Name="LayoutRoot" Background="Transparent">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>

            <!--TitlePanel contains the name of the application and page title-->
            <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
                <TextBlock x:Name="ApplicationTitle" Text="MYAPP" Style="{StaticResource PhoneTextNormalStyle}"/>
                <TextBlock x:Name="PageTitle" Text="settings" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
            </StackPanel>
        <Grid x:Name="ContentGrid" Grid.Row="1">
            <CheckBox Content="CheckBox Setting" Height="Auto" HorizontalAlignment="Left" Margin="60,20,0,0" Name="checkBoxSetting" VerticalAlignment="Top"
            IsChecked="{Binding Source={StaticResource appSettings}, Path=CheckBoxSetting, Mode=TwoWay}"  />

            <ListBox Height="140" HorizontalAlignment="Left" Margin="70,150,0,0" Name="listBoxSetting" 
        VerticalAlignment="Top" Width="360"  SelectedIndex="{Binding Source={StaticResource appSettings}, Path=ListBoxSetting, Mode=TwoWay}">

                <ListBoxItem Content="Times New Roman" FontSize="24" FontFamily="Times New Roman" />
                <ListBoxItem Content="Arial" FontSize="24" FontFamily="Arial" />
                <ListBoxItem Content="Comic Sans MS" FontSize="24" FontFamily="Comic Sans MS" />
            </ListBox>

            <RadioButton Content="Choice One" Height="Auto" HorizontalAlignment="Left" Margin="60,0,0,235" Name="radioButton1" VerticalAlignment="Bottom" GroupName="GroupOne" IsChecked="{Binding Source={StaticResource appSettings}, Path=RadioButton1Setting, Mode=TwoWay}" />
            <RadioButton Content="Choice Two" Height="Auto" HorizontalAlignment="Left" Margin="60,350,0,0" Name="radioButton2" VerticalAlignment="Top" GroupName="GroupOne" IsChecked="{Binding Source={StaticResource appSettings}, Path=RadioButton2Setting, Mode=TwoWay}"/>
            <RadioButton Content="Choice Three" Height="Auto" HorizontalAlignment="Left" Margin="60,400,0,0" Name="radioButton3" VerticalAlignment="Top" GroupName="GroupOne" IsChecked="{Binding Source={StaticResource appSettings}, Path=RadioButton3Setting, Mode=TwoWay}"/>
        </Grid>

    </Grid>



</phone:PhoneApplicationPage>

And the Page1.xaml.cs: 和Page1.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.Diagnostics;



namespace Schedule
{
    public partial class Page1 : PhoneApplicationPage
    {
        // Our settings
        IsolatedStorageSettings settings;

        // The key names of our settings
        const string CheckBoxSettingKeyName = "CheckBoxSetting";
        const string ListBoxSettingKeyName = "ListBoxSetting";
        const string RadioButton1SettingKeyName = "RadioButton1Setting";
        const string RadioButton2SettingKeyName = "RadioButton2Setting";
        const string RadioButton3SettingKeyName = "RadioButton3Setting";
        const string UsernameSettingKeyName = "UsernameSetting";
        const string PasswordSettingKeyName = "PasswordSetting";

        // The default value of our settings
        const bool CheckBoxSettingDefault = true;
        const int ListBoxSettingDefault = 0;
        const bool RadioButton1SettingDefault = true;
        const bool RadioButton2SettingDefault = false;
        const bool RadioButton3SettingDefault = false;
        const string UsernameSettingDefault = "";
        const string PasswordSettingDefault = "";

        /// <summary>
        /// Constructor that gets the application settings.
        /// </summary>
        public Page1()
        {
            InitializeComponent();

            // Get the settings for this application.
            try
            {


                    settings = IsolatedStorageSettings.ApplicationSettings;


            }
            catch(System.IO.IsolatedStorage.IsolatedStorageException e)
            {
                MessageBox.Show(e.ToString());
            }

        }

        /// <summary>
        /// Update a setting value for our application. If the setting does not
        /// exist, then add the setting.
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool AddOrUpdateValue(string Key, Object value)
        {
            bool valueChanged = false;

            // If the key exists
            if (settings.Contains(Key))
            {
                // If the value has changed
                if (settings[Key] != value)
                {
                    // Store the new value
                    settings[Key] = value;
                    valueChanged = true;
                }
            }
            // Otherwise create the key.
            else
            {
                settings.Add(Key, value);
                valueChanged = true;
            }
           return valueChanged;
        }

        /// <summary>
        /// Get the current value of the setting, or if it is not found, set the 
        /// setting to the default setting.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public T GetValueOrDefault<T>(string Key, T defaultValue)
        {
            T value;

            // If the key exists, retrieve the value.
            if (settings.Contains(Key))
            {
                value = (T)settings[Key];
            }
            // Otherwise, use the default value.
            else
            {
                value = defaultValue;
            }
            return value;
        }

        /// <summary>
        /// Save the settings.
        /// </summary>
        public void Save()
        {
            settings.Save();
        }


        /// <summary>
        /// Property to get and set a CheckBox Setting Key.
        /// </summary>
        public bool CheckBoxSetting
        {
            get
            {
                return GetValueOrDefault<bool>(CheckBoxSettingKeyName, CheckBoxSettingDefault);
            }
            set
            {
                if (AddOrUpdateValue(CheckBoxSettingKeyName, value))
                {
                    Save();
                }
            }
        }


        /// <summary>
        /// Property to get and set a ListBox Setting Key.
        /// </summary>
        public int ListBoxSetting
        {
            get
            {
                return GetValueOrDefault<int>(ListBoxSettingKeyName, ListBoxSettingDefault);
            }
            set
            {
                if (AddOrUpdateValue(ListBoxSettingKeyName, value))
                {
                   Save();
                }
            }
        }


        /// <summary>
        /// Property to get and set a RadioButton Setting Key.
        /// </summary>
        public bool RadioButton1Setting
        {
            get
            {
                return GetValueOrDefault<bool>(RadioButton1SettingKeyName, RadioButton1SettingDefault);
            }
            set
            {
                if (AddOrUpdateValue(RadioButton1SettingKeyName, value))
                {    
                    Save();
                }
            }
        }


        /// <summary>
        /// Property to get and set a RadioButton Setting Key.
        /// </summary>
        public bool RadioButton2Setting
        {
            get
            {
                return GetValueOrDefault<bool>(RadioButton2SettingKeyName, RadioButton2SettingDefault);
            }
            set
            {
                if (AddOrUpdateValue(RadioButton2SettingKeyName, value))
                {
                    Save();
                }
            }
        }

        /// <summary>
        /// Property to get and set a RadioButton Setting Key.
        /// </summary>
        public bool RadioButton3Setting
        {
            get
            {
                return GetValueOrDefault<bool>(RadioButton3SettingKeyName, RadioButton3SettingDefault);
            }
            set
            {
                if (AddOrUpdateValue(RadioButton3SettingKeyName, value))
                {
                    Save();
                }
            }
        }

        /// <summary>
        /// Property to get and set a Username Setting Key.
        /// </summary>
        public string UsernameSetting
        {
            get
            {
                return GetValueOrDefault<string>(UsernameSettingKeyName, UsernameSettingDefault);
            }
            set
            {
                if (AddOrUpdateValue(UsernameSettingKeyName, value))
                {
                    Save();
                }
            }
        }

        /// <summary>
        /// Property to get and set a Password Setting Key.
        /// </summary>
        public string PasswordSetting
        {
            get
            {
                return GetValueOrDefault<string>(PasswordSettingKeyName, PasswordSettingDefault);
            }
            set
            {
                if (AddOrUpdateValue(PasswordSettingKeyName, value))
                {
                    Save();
                }
            }

    }
    }
}

Am I would be very happy about any help. 我会很高兴获得任何帮助。 Thanks. 谢谢。

Instead of local:Page1 , you're supposed to put a separate class (named AppSettings in the MSDN sample). 您应该放置一个单独的类(在MSDN示例中命名为AppSettings ,而不是local:Page1

In your case, you have put an instance of Page1 in the XAML of... Page1! 在您的情况下,您已将Page1的实例放在...的XAML中。 Therefore, when the runtime creates Page1, it parses the XAML, find this line of code, create the new Page1 instance, which will in turn create a Page1 instance, and so on... 因此,当运行时创建Page1时,它将解析XAML,查找此行代码,创建新的Page1实例,该实例将依次创建一个Page1实例,依此类推...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用全局类在Windows Phone应用程序中保存数据以用于Windows Phone中的用户设置 - Saving data in Windows Phone application for user settings in Windows Phone using a global class 如何在Windows Phone 8.1中使用Applicationdata类保存登录表单的本地设置 - How to save local settings of login form using Applicationdata class in windows phone 8.1 应用程序设置Windows Phone 8 - Application settings Windows phone 8 存储Windows Phone的设置 - Storing Settings for Windows Phone 在Windows Phone应用程序中使用应用程序数据和本地设置 - using application data and local settings in windows phone applications 如何在Windows Phone中使用列表框绑定诸如gridview之类的数据 - How to bind data like gridview using listbox in windows phone 使用ItemsControl将按钮绑定到画布Windows Phone的顶部/左侧位置 - Using ItemsControl to bind buttons top/left position on canvas Windows Phone 从Windows Phone的“设置”页面传播设置 - Propagating settings from the Settings page on Windows Phone Windows Phone 7在设置部分为应用程序创建设置 - Windows phone 7 create settings for application in settings section 打开/关闭Windows Phone设置 - Turn Windows Phone Settings On/Off
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM