- 追加された行はこの色です。
- 削除された行はこの色です。
&tag(WPF/設定を保存する);
&tag(WPF, 設定を保存する);
*目次 [#rc2142b8]
#contents
*参考情報 [#n2533f35]
-[[.net - c# - approach for saving user settings in a WPF application? - Stack Overflow:http://stackoverflow.com/questions/3784477/c-approach-for-saving-user-settings-in-a-wpf-application]]
-[[User Settings Applied - CodeProject:http://www.codeproject.com/KB/dotnet/user_settings.aspx]]
-[[Configuring Application/User Settings in WPF the easy way.:http://geekswithblogs.net/mbcrump/archive/2010/06/17/configuring-applicationuser-settings-in-wpf-the-easy-way.aspx]]
*Settings.settingsを使う方法 [#tb8c70cd]
**基本 [#v8902b74]
-<プロジェクトルート>\PropertiesにあるSettings.settingsを使う方法が一番簡単らしい。
-Settings.settingsの内容はapp.configというxmlファイルに保存され、これが実行時に変更される実際の情報保存用ファイルのひな形となる。
-実行時の情報保存様ファイルは〜.exe.configというファイルで、exeと同じフォルダに存在する。
**サンプル [#v8d5b331]
***概要 [#ve9b5a09]
-Messageという文字列型の設定値を保存する。
-保存ボタンを押したら保存する
**設定値の作成 [#af0ca5e3]
-Messageという文字列型の設定値をTextBoxにバインドする。
-保存ボタンを押したら保存。次回に同じ値が読み込まれる。
***設定値の作成 [#af0ca5e3]
-ソリューションエクスプローラーでProperties\Settings.settingsを開き以下の項目を追加する。
,名前,型,スコープ
,Message,string,ユーザー
**MainWindow.xaml [#gf27ef4b]
-MainWindowViewModelのメッセージプロパティをTextにバインド。
***MainWindow.xaml [#gf27ef4b]
-DataContext(=MainWindowViewModel)のMessageプロパティをTextにバインド。
-保存ボタンをおしたときハンドラで保存する。
#pre{{
<Window x:Class="SettingsDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="200">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<TextBox Margin="10" Text="{Binding Message}"></TextBox>
<Button Grid.Row="1" Click="button_Clicked">保存</Button>
</Grid>
</Window>
}}
**MainWindow.xaml.cs [#o3893223]
-MainWindowViewModelをDataContextにバインド。
***MainWindow.xaml.cs [#o3893223]
-MainWindowViewModelをDataContextに代入。。
-保存ボタンが押されたときのイベントハンドラbutton_Clickedで設定値を保存。
#pre{{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
private void button_Clicked(object sender, RoutedEventArgs e)
{
Properties.Settings.Default.Save();
}
}
}}
**MainWindowViewModel.cs [#g2c225fa]
***MainWindowViewModel.cs [#g2c225fa]
-MessageプロパティはProperties.Settings.Default.MessageのDelegateメソッドとする。
#pre{{
public class MainWindowViewModel :INotifyPropertyChanged
{
public string Message
{
get
{
return Properties.Settings.Default.Message;
}
set
{
Properties.Settings.Default.Message = value;
NotifyPropertyChanged("Message");
}
}
#region INotifyPropertyChanged メンバー
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}}