C# WPF:静态类属性上的双向绑定
我想将文本框文本绑定到静态属性,例如,但无法使其工作。智能感知也没有帮助C# WPF:静态类属性上的双向绑定,c#,wpf,C#,Wpf,我想将文本框文本绑定到静态属性,例如,但无法使其工作。智能感知也没有帮助 静态配置类: WPF窗口: 我尝试过的东西: {Binding Path={x:Static local:Configuration.Host},UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}-调用了Getter,但无效的castexpation:System.String System.Windows.PropertyPath {Binding Source={
静态配置类: WPF窗口:
我尝试过的东西:
-调用了Getter,但无效的castexpation:System.String System.Windows.PropertyPath{Binding Path={x:Static local:Configuration.Host},UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}
-调用Getter,invalidOperationException:双向绑定需要路径或XPath{Binding Source={x:Static local:Configuration.Host},Mode=TwoWay}
正确调用并显示了Getter,但没有Setter{Binding Source={x:Static local:Configuration.Host},Mode=TwoWay,Path=.}
-调用了Getter但未显示,Setter未工作`{Binding{x:Static local:Configuration.Host},Mode=TwoWay}
编辑:为什么它不是重复的
是关于非静态类中的静态属性的。我问的是静态类中的静态属性。引用:“如果类不是静态的”。配置是一个静态类。您是否阅读了第二个答案,包括注释?双向绑定需要一个路径(然后源需要是运行路径的对象)。您试图绑定到类型而不是对象,这适用于单向绑定,但与双向绑定固有的工作方式冲突。为什么不改用单例呢?是的,但我想避免单例模式。答案是从2009年开始的,我猜从那时起微软可能已经在WPF中添加了一些功能。可能会有帮助。谢谢@Clemens。这的确是正确的答案。引用:“假设类不是静态的”。配置是一个静态类。您是否阅读了第二个答案,包括注释?双向绑定需要一个路径(然后源需要是运行路径的对象)。您试图绑定到类型而不是对象,这适用于单向绑定,但与双向绑定固有的工作方式冲突。为什么不改用单例呢?是的,但我想避免单例模式。答案是从2009年开始的,我猜从那时起微软可能已经在WPF中添加了一些功能。可能会有帮助。谢谢@Clemens。这的确是正确的答案。
public static class Configuration
{
public static string Host { get; set; } = "127.0.0.1";
}
<Window x:Class="MyApp.OptionsDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyApp"
mc:Ignorable="d"
Title="OptionsDialog" Height="104.563" Width="226.845">
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Content="Host: " Grid.Column="0" Grid.Row="0"/>
<TextBox Text="{Binding Source=x:Static local:Configuration.Host}" Grid.Column="1" Grid.Row="0" Margin="1"/>
</Grid>
</Window>