在 C# 中将 WPF 属性绑定到 ApplicationSettings 的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/154533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to bind WPF properties to ApplicationSettings in C#?
提问by Kris Erickson
What is the best way to bind WPF properties to ApplicationSettings in C#? Is there an automatic way like in a Windows Forms Application? Similar to this question, how (and is it possible to) do you do the same thing in WPF?
在 C# 中将 WPF 属性绑定到 ApplicationSettings 的最佳方法是什么?是否有类似于 Windows 窗体应用程序的自动方式?与这个问题类似,您如何(并且有可能)在 WPF 中做同样的事情?
采纳答案by Sacha Bruttin
You can directly bind to the static object created by Visual Studio.
您可以直接绑定到 Visual Studio 创建的静态对象。
In your windows declaration add:
在您的 Windows 声明中添加:
xmlns:p="clr-namespace:UserSettings.Properties"
where UserSettings
is the application namespace.
UserSettings
应用程序命名空间在哪里。
Then you can add a binding to the correct setting:
然后您可以将绑定添加到正确的设置:
<TextBlock Height="{Binding Source={x:Static p:Settings.Default},
Path=Height, Mode=TwoWay}" ....... />
Now you can save the settings, per example when you close your application:
现在,您可以在关闭应用程序时保存设置,例如:
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
Properties.Settings.Default.Save();
base.OnClosing(e);
}
回答by Alan Le
Kris, I'm not sure this is the best way to bind ApplicationSettings, but this is how I did it in Witty.
Kris,我不确定这是绑定 ApplicationSettings 的最佳方式,但我在Witty 中就是这样做的。
1) Create a dependency property for the setting that you want to bind in the window/page/usercontrol/container. This is case I have an user setting to play sounds.
1)在window/page/usercontrol/container中为要绑定的设置创建一个依赖属性。在这种情况下,我有一个用户设置来播放声音。
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) In the constructor, initialize the property value to match the application settings
2) 在构造函数中,初始化属性值以匹配应用程序设置
PlaySounds = Properties.Settings.Default.PlaySounds;
3) Bind the property in XAML
3)在XAML中绑定属性
<CheckBox Content="Play Sounds on new Tweets" x:Name="PlaySoundsCheckBox" IsChecked="{Binding Path=PlaySounds, ElementName=Window, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
You can download the full Witty sourceto see it in action or browse just the code for options window.
回答by rudigrobler
回答by Richard Szalay
The easiest way would be to bind to an object that exposes your application settings as properties or to include that object as a StaticResource and bind to that.
最简单的方法是绑定到将应用程序设置公开为属性的对象,或者将该对象包含为 StaticResource 并绑定到该对象。
Another direction you could take is creation your own Markup Extensionso you can simply use PropertyName="{ApplicationSetting SomeSettingName}". To create a custom markup extension you need to inherit MarkupExtensionand decorate the class with a MarkupExtensionReturnTypeattribute. John Bowenhas a post on creating a custom MarkupExtensionthat might make the process a little clearer.
您可以采取的另一个方向是创建您自己的标记扩展,以便您可以简单地使用 PropertyName="{ApplicationSetting SomeSettingName}"。要创建自定义标记扩展,您需要继承MarkupExtension并使用MarkupExtensionReturnType属性装饰该类。John Bowen有一篇关于创建自定义 MarkupExtension的帖子,这可能会使过程更清晰一些。
回答by Remus
I like the accepted answer, I ran into a special case though. I had my text box set as "read only" so that I can change the value of it only in the code. I couldn't understand why the value wasn't propagated back to the Settings although I had the Mode as "TwoWay".
我喜欢接受的答案,但我遇到了一个特殊情况。我将文本框设置为“只读”,以便我只能在代码中更改它的值。尽管我的模式为“双向”,但我无法理解为什么该值没有传播回设置。
Then, I found this: http://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx
然后,我发现了这个:http: //msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx
The default is Default, which returns the default UpdateSourceTrigger value of the target dependency property. However, the default value for most dependency properties is PropertyChanged, while the Text property has a default value of LostFocus.
默认为 Default,它返回目标依赖属性的默认 UpdateSourceTrigger 值。但是,大多数依赖项属性的默认值是 PropertyChanged,而Text 属性的默认值是 LostFocus。
Thus, if you have the text box with IsReadOnly="True" property, you have to add a UpdateSourceTrigger=PropertyChanged value to the Binding statement:
因此,如果您的文本框具有 IsReadOnly="True" 属性,则必须向 Binding 语句添加 UpdateSourceTrigger=PropertyChanged 值:
<TextBox Text={Binding Source={x:Static p:Settings.Default}, Path=myTextSetting, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged} ... />
回答by TknoSpz
In case you are a VB.Netdeveloper attempting this, the answer is a smidge different.
如果您是尝试此操作的VB.Net开发人员,则答案略有不同。
xmlns:p="clr-namespace:ThisApplication"
Notice the .Properties isn't there.
注意 .Properties 不存在。
In your binding it's MySettings.Default, instead of Settings.Default - since the app.config stores it differently.
在您的绑定中,它是 MySettings.Default,而不是 Settings.Default - 因为 app.config 以不同的方式存储它。
<TextBlock Height={Binding Source={x:Static p:MySettings.Default}, Path=Height, ...
After a bit of pulling out my hair, I discovered this. Hope it helps
拔了一点头发后,我发现了这一点。希望能帮助到你
回答by NathofGod
I like to do it through the ViewModel and just do the binding as normal in the XAML
我喜欢通过 ViewModel 来做,只是在 XAML 中像往常一样进行绑定
public Boolean Value
{
get
{
return Settings.Default.Value;
}
set
{
Settings.Default.SomeValue= value;
Settings.Default.Save();
Notify("SomeValue");
}
}