방법: Windows Phone의 설정 페이지 만들기
2012-02-09
이 항목에서는 Windows Phone 응용프로그램의 설정 페이지를 만드는 데 필요한 단계를 소개합니다. 이 완성된 설정 샘플은 Windows Phone용 코드 샘플 항목에서 확인할 수 있습니다.
Windows Phone 응용프로그램의 설정 페이지를 만드는 첫 번째 단계는 설정을 포함할 클래스를 만들고 격리된 저장소에 설정을 저장 및 로드하는 것입니다. 설정을 키-값 쌍으로 격리된 저장소에 저장하는 방법에 대한 자세한 내용은 IsolatedStorageSettings 클래스를 참조하십시오. 일반적인 격리된 저장소에 대한 자세한 내용은 Windows Phone의 로컬 데이터 저장소를 참조하십시오.
이 클래스에는 격리된 저장소에 값을 추가하거나 업데이트하는 메서드가 포함됩니다. 다음 코드에서는 이 메서드를 AddOrUpdateValue라고 합니다. 값을 읽거나, 설정이 지정되지 않은 경우 기본값을 할당하는 메서드도 있습니다. 다음 코드에서는 이 메서드를 GetValueOrDefault라고 합니다.
각 설정이나 속성에 대해 접근자 함수가 있습니다. 다음 코드에는 CheckBoxSetting, ListBoxSetting 및 PasswordSetting이라는 여러 함수가 있습니다. 고유한 접근자 함수에 추가하여 고유한 속성을 추가할 수 있습니다. 각 설정에 대해 격리된 저장소 키 이름을 정의하는 문자열 상수와 기본값을 정의하는 상수가 있습니다.
using System; using System.IO.IsolatedStorage; using System.Diagnostics; using System.Collections.Generic; namespace SettingsSample { public class AppSettings { // Our isolated storage settings IsolatedStorageSettings settings; // The isolated storage 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 AppSettings() { // Get the settings for this application. settings = IsolatedStorageSettings.ApplicationSettings; } /// <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(); } } } } }
사용자가 확인 버튼을 누를 필요가 없는 페이지의 경우 데이터 바인딩을 사용하여 설정 변경 사항을 즉시 적용하고 값을 격리된 저장소에 저장할 수 있습니다. 모든 변경 사항은 설정 페이지의 XAML에서 수행됩니다. TwoWay의 데이터 바인딩 모드에서는 변경 사항을 즉시 적용합니다.
![]() |
---|
설정 페이지의 UI를 디자인하는 방법에 대한 자세한 내용은 Windows Phone의 사용자 환경 디자인 지침을 참조하십시오. |
먼저 xmlns:local="clr-namespace:SettingsSample" 네임스페이스 선언을 추가합니다.
x:Class="SettingsSample.SettingsWithoutConfirmation" 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:SettingsSample" 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">
<local:AppSettings x:Key="appSettings"></local:AppSettings> 로컬 리소스를 추가합니다.
<phone:PhoneApplicationPage.Resources> <local:AppSettings x:Key="appSettings"></local:AppSettings> </phone:PhoneApplicationPage.Resources>
페이지의 각 설정에 대해 속성과 컨트롤 간의 데이터 바인딩을 설정합니다.
<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>
추가 코드나 작업은 필요하지 않습니다. 설정 페이지가 완성되었습니다.
사용자 이름 또는 비밀번호와 같은 텍스트 입력이 필요한 설정에서는 사용자가 입력 완료 시 확인 버튼을 눌러야 할 수도 있습니다. 이러한 설정 페이지의 경우 생성자에 응용프로그램 모음을 추가하여 OK 및 Cancel 버튼을 페이지에 추가할 수 있습니다.
사용자가 확인 버튼을 눌러야 하는 페이지의 경우 단방향 데이터 바인딩을 사용하여 현재 값을 로드할 수 있지만 사용자 변경 사항이 즉시 적용되지 않습니다.
먼저 xmlns:local="clr-namespace:SettingsSample" 네임스페이스 선언을 추가합니다.
x:Class="SettingsSample.SettingsWithConfirmation" 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:SettingsSample" 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">
<local:AppSettings x:Key="appSettings"></local:AppSettings> 로컬 리소스를 추가합니다.
<phone:PhoneApplicationPage.Resources> <local:AppSettings x:Key="appSettings"></local:AppSettings> </phone:PhoneApplicationPage.Resources>
페이지의 각 설정에 대해 속성과 컨트롤 간의 단방향 데이터 바인딩을 설정합니다.
<Grid x:Name="ContentGrid" Grid.Row="1"> <TextBlock Height="60" HorizontalAlignment="Left" Margin="65,12,0,0" Name="textBlock1" Text="Username" VerticalAlignment="Top" Width="169" /> <TextBox Height="78" HorizontalAlignment="Left" Margin="60,60,0,0" Name="textBoxUsername" Text="{Binding Path=UsernameSetting, Mode=OneWay, Source={StaticResource appSettings}}" VerticalAlignment="Top" Width="274" /> <TextBlock Height="60" HorizontalAlignment="Left" Margin="65,160,0,0" Name="textBlock2" Text="Password" VerticalAlignment="Top" Width="169" /> <PasswordBox Height="78" HorizontalAlignment="Left" Margin="60,208,0,0" Name="passwordBoxPassword" Password="{Binding Path=PasswordSetting, Mode=OneWay, Source={StaticResource appSettings}}" VerticalAlignment="Top" Width="274" /> </Grid>
페이지의 생성자에 OK 및 Cancel 버튼이 있는 응용프로그램 모음을 추가합니다.
public SettingsWithConfirmation() { InitializeComponent(); // Add an Application Bar that has a 'done' confirmation button and // a 'cancel' button ApplicationBar = new ApplicationBar(); ApplicationBar.IsMenuEnabled = true; ApplicationBar.IsVisible = true; ApplicationBar.Opacity = 1.0; ApplicationBarIconButton doneButton = new ApplicationBarIconButton(new Uri("/Images/appbar.check.rest.png", UriKind.Relative)); doneButton.Text = "done"; doneButton.Click += new EventHandler(doneButton_Click); ApplicationBarIconButton cancelButton = new ApplicationBarIconButton(new Uri("/Images/appbar.cancel.rest.png", UriKind.Relative)); cancelButton.Text = "cancel"; cancelButton.Click += new EventHandler(cancelButton_Click); ApplicationBar.Buttons.Add(doneButton); ApplicationBar.Buttons.Add(cancelButton); }
사용자가 변경 사항을 확인하면 값이 저장됩니다.
void doneButton_Click(object sender, EventArgs e) { settings.UsernameSetting = textBoxUsername.Text; settings.PasswordSetting = passwordBoxPassword.Password; NavigationService.GoBack(); }
하지만 사용자가 변경 사항을 취소하면 저장하지 않고 페이지를 벗어난 부분을 탐색합니다.
void cancelButton_Click(object sender, EventArgs e) { NavigationService.GoBack(); }
'WINDOWS PHONE' 카테고리의 다른 글
응용프로그램의 시험판 환경 구현 (0) | 2013.02.11 |
---|---|
db 업데이트 하기. (0) | 2013.02.07 |
로컬 데이터베이스 업데이트 (0) | 2013.02.02 |
SQL Server Compact 4.0 데이터 형식 (0) | 2013.02.01 |
Windows Phone의 응용프로그램 제목 지역화 (0) | 2013.01.29 |