如何在C#中将WPF属性绑定到ApplicationSettings中?是否有自动方式类似于Windows Forms应用程序?与此问题类似,如何(是否有可能)在WPF中实现相同的绑定方式?
如何在C#中将WPF属性绑定到ApplicationSettings中?是否有自动方式类似于Windows Forms应用程序?与此问题类似,如何(是否有可能)在WPF中实现相同的绑定方式?
xmlns:p="clr-namespace:UserSettings.Properties"
其中 UserSettings
是应用程序命名空间。
然后,您可以将绑定添加到正确的设置:
<TextBlock Height="{Binding Source={x:Static p:Settings.Default},
Path=Height, Mode=TwoWay}" ....... />
现在,您可以保存设置,例如当您关闭应用程序时:
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
Properties.Settings.Default.Save();
base.OnClosing(e);
}
xmlns:p="clr-namespace:ThisApplication"
注意,这里没有.Properties。
在你的绑定中,应该使用MySettings.Default而不是Settings.Default——因为app.config中存储方式不同。
<TextBlock Height={Binding Source={x:Static p:MySettings.Default}, Path=Height, ...
在我抓耳挠腮一阵之后,我发现了这个。希望它可以帮到你。
<TextBox Text={Binding Source={x:Static p:Settings.Default}, Path=myTextSetting, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged} ... />
我喜欢通过ViewModel来实现,然后在XAML中像正常绑定一样进行绑定。
public Boolean Value
{
get
{
return Settings.Default.Value;
}
set
{
Settings.Default.SomeValue= value;
Settings.Default.Save();
Notify("SomeValue");
}
}
Kris,我不确定这是绑定ApplicationSettings的最佳方法,但这就是我在Witty中所做的。
1)为您想要在窗口/页面/用户控件/容器中绑定的设置创建一个依赖属性。在这种情况下,我有一个用户设置来播放声音。
public bool PlaySounds
{
get { return (bool)GetValue(PlaySoundsProperty); }
set { SetValue(PlaySoundsProperty, value); }
}
public static readonly DependencyProperty PlaySoundsProperty =
DependencyProperty.Register("PlaySounds", typeof(bool), typeof(Options),
new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnPlaySoundsChanged)));
private static void OnPlaySoundsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
Properties.Settings.Default.PlaySounds = (bool)args.NewValue;
Properties.Settings.Default.Save();
}
2) 在构造函数中,将属性值初始化为与应用程序设置相匹配的值
PlaySounds = Properties.Settings.Default.PlaySounds;
3) 在XAML中绑定属性
<CheckBox Content="Play Sounds on new Tweets" x:Name="PlaySoundsCheckBox" IsChecked="{Binding Path=PlaySounds, ElementName=Window, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
TwoWay
绑定实际上是双向工作的。很好。+1 - Adam Badura