Skip to content

Instantly share code, notes, and snippets.

@jTakasuRyuji
Created September 12, 2023 13:19
Show Gist options
  • Select an option

  • Save jTakasuRyuji/4d33b205dd85c976302899e5c424ccef to your computer and use it in GitHub Desktop.

Select an option

Save jTakasuRyuji/4d33b205dd85c976302899e5c424ccef to your computer and use it in GitHub Desktop.
[UWP]コードからバインディングを設定してLocalSettingsの読み書きを行う
<Grid>
<StackPanel Width="400" Margin="50">
<!--First name-->
<TextBlock Text="First name:" />
<TextBox Text="{x:Bind ViewModel.FirstName, Mode=TwoWay}"/>
<!--Last name-->
<TextBlock Text="Last name:" />
<TextBox Text="{x:Bind ViewModel.LastName, Mode=TwoWay}" />
<!--Age-->
<TextBlock Text="Age:" />
<TextBox Text="{x:Bind ViewModel.Age, Mode=TwoWay}" />
</StackPanel>
</Grid>
public sealed partial class MainPage : Page
{
public PersonViewModel ViewModel { get; set; } = new PersonViewModel();
public MainPage()
{
this.InitializeComponent();
}
}
public class PersonViewModel
{
private string _FirstName;
private string _LastName;
private int _Age;
//個別に更新
public string FirstName {
get { return _FirstName; }
set { _FirstName = value;
localSettings.Values[firstNameKey] = FirstName;
}
}
public string LastName
{
get { return _LastName; }
set { _LastName = value;
localSettings.Values[lastNameKey] = _LastName;
}
}
public int Age
{
get { return _Age; }
set { _Age = value;
localSettings.Values[ageKey] = _Age;
}
}
// The rest of the class definition
private ApplicationDataContainer localSettings =
ApplicationData.Current.LocalSettings;
private string firstNameKey = nameof(FirstName);
private string lastNameKey = nameof(LastName);
private string ageKey = nameof(Age);
/// <summary>
/// 全部Write  
/// </summary>
public void StoreInSettings()
{
localSettings.Values[firstNameKey] = FirstName;
localSettings.Values[lastNameKey] = LastName;
localSettings.Values[ageKey] = Age;
}
/// <summary>
/// ctor
/// </summary>
public PersonViewModel()
{
if (IsPersonDataStoredInSettings())
{
FirstName = localSettings.Values[firstNameKey]?.ToString();
LastName = localSettings.Values[lastNameKey]?.ToString();
Age = (int)localSettings.Values[ageKey];
}
}
/// <summary>
/// データの存在確認
/// </summary>
/// <returns>1つでも見つからなかったらFalse</returns>
private bool IsPersonDataStoredInSettings()
{
string[] keys = { firstNameKey, lastNameKey, ageKey };
var isPersonDataStoredInSettings = true;
foreach (var key in keys)
{
if (!localSettings.Values.ContainsKey(key))
{
isPersonDataStoredInSettings = false;
break;
}
}
return isPersonDataStoredInSettings;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment