Matt Hamilton告诉我一个关于WPF的有趣事实:在4.5版本中,可以使用静态变量以双向模式进行绑定。 不幸的是,V4.5仍然是测试版,我决定更改我的代码以使我的应用程序最终运行正确。双向绑定在WPF中无法与静态成员一起工作
但是 - 我仍然有类似的问题,在这里我们去:
我有一个非常简单的类“RecallConnectionSettings”。这个类的该成员应当从无处不在的代码访问,所以我决定让他们静态的(像这样):
public class RecallConnectionSettings
{
private static string Server {get;set;}
}
正如你可以看到:只有一个变量“服务器”。 现在我想要的是将2WayMode从TextBox文本属性绑定到该“服务器”值。
所以,我想这一点:
<UserControl....>
<UserControl.Resources>
<local:RecallConnectionSettings x:Key="recallConf"/>
</UserControl.Resources>
<TextBox Text="{Binding Source={StaticResource recallConf}, Path=Server,
Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ... Name="txtServerAdress" />
</UserControl>
当我改变文本框中的值,这个伟大的工程 - 而不是从另一面。 如果我(手动)更改“服务器”值,我的文本框中的文本属性将不会更新。
当然不是 - 因为我现在知道我必须在RecallConnectionSettings类中实现INotifyProperty。 然后,它看起来是这样的:
public class RecallConnectionSettings : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private static string s_server;
public static string Server
{
get { return s_server; }
set
{
s_server = value;
OnPropertyChanged("Server");
}
}
public static event PropertyChangedEventHandler PropertyChanged;
protected static void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
好 - 这不能工作过。因为只有静态方法,我不能使用类的实例调用事件:
PropertyChanged(this, new PropertyChangedEventArgs(name));
那么 - 现在怎么办? 我想过使用一个单身,所以我这样做:
public class RecallConnectionSettings : INotifyPropertyChanged
{
private static RecallConnectionSettings instance;
private RecallConnectionSettings(){}
public static RecallConnectionSettings Instance
{
get
{
if(instance == null)
{
instance = new RecallConnectionSettings();
}
return instance;
}
}
// ... here comes the other stuff
}
要使其工作,我也有准备我的用户,所以我这样做:
...
<UserControl.DataContext>
<local:RecallConnectionSettings/>
</UserControl.DataContext>
...
在这一点上,不需要继续尝试,因为为此,默认构造函数必须是公共的。
不管我在做什么:它不起作用。 在我看来,我仍然不明白这是如何工作的 - 你会如此善良,向我展示这个诀窍?
你不应该从INotifyPropertyChanged的派生? – stijn 2012-04-18 10:25:01
VS中的“输出 - 调试”显示了什么? 您是否在绑定中激活了调试? 像@stijn说,你需要从INotifyPropertyChanged派生 – 2012-04-18 10:27:18
该死的 - 你是对的..我会再试一次。谢谢。 – CodeCannibal 2012-04-18 10:27:38