Equivalent to UserSettings / ApplicationSettings in WPF dotnet core

前端 未结 6 1337
没有蜡笔的小新
没有蜡笔的小新 2020-12-23 16:32

What is the prefered way for persisting user settings for WPF applications with .Net Core >=3.0?

Created WPF .Net Core 3.0 Project (VS2019 V16.3.1) Now I have seen t

6条回答
  •  余生分开走
    2020-12-23 17:01

    You can use a Nuget package System.Configuration.ConfigurationManager. It is compatible with .Net Standard 2.0, so it should be usable in .Net Core application.

    There is no designer for this, but otherwise it works the same as .Net version, and you should be able to just copy the code from your Settings.Designer.cs. Also, you can override OnPropertyChanged, so there's no need to call Save.

    Here's an example, from the working .Net Standard project:

    public class WatchConfig: ApplicationSettingsBase
    {
        static WatchConfig _defaultInstance = (WatchConfig)Synchronized(new WatchConfig());
    
        public static WatchConfig Default { get => _defaultInstance; }
    
        protected override void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            Save();
            base.OnPropertyChanged(sender, e);
        }
    
        [UserScopedSetting]
        [global::System.Configuration.DefaultSettingValueAttribute(
        @"
        
          C:\temp
         ..\otherdir
         ")]
        public StringCollection Directories
        {
            get { return (StringCollection)this[nameof(Directories)]; }
            set { this[nameof(Directories)] = value; }
        }
    }
    

提交回复
热议问题