公共Settings类中属性化变量的C#与XAML访问语法咨询
正确实现与语法示例
第一步:确保StandardSettings类的FilePath属性封装正确
先基于Preferences类完成属性的正确封装,自动处理配置的保存与加载,示例代码如下:
public class StandardSettings { // 定义配置键名常量,避免硬编码错误 private const string FilePathKey = "FilePath"; // 设置默认值 private const string DefaultFilePath = ""; // 封装FilePath属性 public static string FilePath { get => Preferences.Get(FilePathKey, DefaultFilePath); set => Preferences.Set(FilePathKey, value); } }
C#中的获取与设置语法
获取FilePath
直接访问静态属性即可,无需额外方法调用:
// 获取配置值 string filePath = StandardSettings.FilePath; // 赋值给控件属性示例 myTextBox.Text = StandardSettings.FilePath;
设置FilePath
直接给属性赋值,自动保存到Preferences:
StandardSettings.FilePath = @"C:\Users\Example\Documents\target.txt";
XAML中的获取与设置语法
绑定静态属性
如果FilePath是静态属性,使用x:Static标记实现绑定:
<!-- 读取配置值 --> <TextBox Text="{x:Static local:StandardSettings.FilePath}" />
若需要双向绑定(修改控件内容后自动保存配置),需结合属性变更通知。比如使用CommunityToolkit.Mvvm简化实现:
public partial class StandardSettings { private const string FilePathKey = "FilePath"; private const string DefaultFilePath = ""; [ObservableProperty] private static string _filePath = Preferences.Get(FilePathKey, DefaultFilePath); // 属性变更时自动保存到Preferences partial void OnFilePathChanged(string value) { Preferences.Set(FilePathKey, value); } }
对应的双向绑定XAML:
<TextBox Text="{Binding Source={x:Static local:StandardSettings.FilePath}, Mode=TwoWay}" />
绑定实例属性(若StandardSettings为普通实例类)
先在XAML中实例化类作为资源:
<Window.Resources> <local:StandardSettings x:Key="AppSettings" /> </Window.Resources>
再绑定到实例属性:
<TextBox Text="{Binding FilePath, Source={StaticResource AppSettings}, Mode=TwoWay}" />
内容的提问来源于stack exchange,提问作者canedha
相关产品推荐
相关产品推荐

