C# 设置Binding.Path在某些计算机上引发异常
考虑下面的例子C# 设置Binding.Path在某些计算机上引发异常,c#,.net,wpf,xaml,data-binding,C#,.net,Wpf,Xaml,Data Binding,考虑下面的例子 public class Test { private static string _property = "Success"; public static string Property { get { return _property; } set { _property = value; } } public void Check() { var prop = new Pro
public class Test
{
private static string _property = "Success";
public static string Property
{
get { return _property; }
set { _property = value; }
}
public void Check()
{
var prop = new PropertyPath(this.GetType().GetProperty("Property"));
var binding = new Binding();
binding.Source = typeof(Test);
binding.Path = prop;
}
public static void DoTest()
{
new Test().Check();
}
}
当我调用
Test.DoTest()
时,它在我的机器上工作正常,但在其他一些机器上抛出invalidoOperationException
消息,如“使用Binding.Source时无法分配Binding.StaticSource”(这不是准确的翻译文本)。如果属性不是静态的,那么一切都可以工作。什么可能导致这种行为?我猜您正在测试的机器有不同的框架版本,并且由于.NET 4.5中的这个新功能,您正在运行不兼容:我猜您正在测试的机器有不同的框架版本,并且您正在运行不兼容NET 4.5中的新功能:我4年前就开始使用WPF了……我不记得所有这些,但使用它可能会有用
public class Test : DependencyObject
{
public static readonly DependencyProperty FilterStringProperty =
DependencyProperty.Register("Property", typeof(string),
typeof(Test), new UIPropertyMetadata("Success"));
public string Property
{
get { return (string)GetValue(FilterStringProperty); }
set { SetValue(FilterStringProperty, value); }
}
public static Test Instance { get; private set; }
static Test()
{
}
public void Check()
{
var prop = new PropertyPath(this.GetType().GetProperty("Property"));
var binding = new Binding();
binding.Source = this;
//binding.Source = typeof(Test); //-- same thing
binding.Path = prop;
}
public static void DoTest()
{
Instance = new Test();
new Test().Check();
}
}
我在4年前就开始使用WPF了……我不记得所有这些,但使用它可能会有用
public class Test : DependencyObject
{
public static readonly DependencyProperty FilterStringProperty =
DependencyProperty.Register("Property", typeof(string),
typeof(Test), new UIPropertyMetadata("Success"));
public string Property
{
get { return (string)GetValue(FilterStringProperty); }
set { SetValue(FilterStringProperty, value); }
}
public static Test Instance { get; private set; }
static Test()
{
}
public void Check()
{
var prop = new PropertyPath(this.GetType().GetProperty("Property"));
var binding = new Binding();
binding.Source = this;
//binding.Source = typeof(Test); //-- same thing
binding.Path = prop;
}
public static void DoTest()
{
Instance = new Test();
new Test().Check();
}
}
4.5是CLR的就地升级,因此即使在安装了4.5的计算机上运行4.0应用程序,也会运行在4.5 CLR上,其行为可能略有不同。不确定这是否是您的问题,但这应该是您检查的第一件事。4.5是CLR的就地升级,因此即使在安装了4.5的计算机上运行4.0应用程序,也会与4.5 CLR运行,其行为可能略有不同。不确定这是否是您的问题,但这应该是您检查的第一件事。如果您以未实现的Framework 4.0为目标,您希望如何绑定到静态属性?@LPL它在我只安装了.net 4.0的机器上工作。事实上,我只需要单向源绑定。如果您的目标是Framework 4.0,而它没有实现,您希望如何绑定到静态属性?@LPL它可以在我的机器上工作,而我的机器上只安装了.net 4.0。实际上,我只需要一种方式来源绑定。