Created
May 12, 2014 19:33
-
-
Save Injac/59f310d0e46874df7514 to your computer and use it in GitHub Desktop.
SettingsBehavior to save Roamed Settings (attach to TextBox) in WinRT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Microsoft.Xaml.Interactivity.TypeConstraint(typeof(Windows.UI.Xaml.Controls.TextBox))] | |
class SettingsBehavior : DependencyObject, IBehavior | |
{ | |
#region IBehavior Members | |
public Windows.UI.Xaml.DependencyObject AssociatedObject { get; set; } | |
public string SettingsIndex | |
{ | |
get { return (string)GetValue(SettingsIndexProperty); } | |
set { SetValue(SettingsIndexProperty, value); } | |
} | |
// Using a DependencyProperty as the backing store for SettingsIndex. This enables animation, styling, binding, etc... | |
public static readonly DependencyProperty SettingsIndexProperty = | |
DependencyProperty.Register("SettingsIndex", typeof(string), typeof(SettingsBehavior), new PropertyMetadata(string.Empty)); | |
public void Attach(Windows.UI.Xaml.DependencyObject associatedObject) | |
{ | |
this.AssociatedObject = associatedObject; | |
TextBox txt = null; | |
if (this.AssociatedObject is TextBox) | |
{ | |
txt = this.AssociatedObject as TextBox; | |
txt.TextChanged += txt_TextChanged; | |
txt.Loaded += txt_Loaded; | |
} | |
} | |
void txt_Loaded(object sender, RoutedEventArgs e) | |
{ | |
var txt = sender as TextBox; | |
if (ApplicationData.Current.RoamingSettings.Values.ContainsKey(this.SettingsIndex)) | |
{ | |
txt.Text = ApplicationData.Current.RoamingSettings.Values[this.SettingsIndex] as string; | |
} | |
} | |
void txt_TextChanged(object sender, TextChangedEventArgs e) | |
{ | |
var txt = sender as TextBox; | |
ApplicationData.Current.RoamingSettings.Values[this.SettingsIndex] = txt.Text; | |
} | |
public void Detach() | |
{ | |
if (this.AssociatedObject != null) | |
{ | |
TextBox txt = null; | |
if (this.AssociatedObject is TextBox) | |
{ | |
txt = this.AssociatedObject as TextBox; | |
txt.TextChanged -= txt_TextChanged; | |
txt.Loaded -= txt_Loaded; | |
} | |
} | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment