【问题标题】:Setting Binding.Path throws exception on some machines在某些机器上设置 Binding.Path 会引发异常
【发布时间】:2013-05-15 18:55:10
【问题描述】:

考虑下面的例子

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() 时,它在我的机器上运行良好,但在其他一些机器上抛出了类似“使用 Binding.Source 时无法分配 Binding.StaticSource”的消息(这不准确,翻译文本)。如果属性不是静态的,那么一切正常。什么可能导致这种行为?

【问题讨论】:

  • 如果您的目标是未实现的 Framework 4.0,您希望如何绑定到静态属性?
  • @LPL 它可以在我只安装 .net 4.0 的机器上运行。其实我只需要 OneWayToSource 绑定。

标签: c# .net wpf xaml data-binding


【解决方案1】:

我在 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();
    }
}

【讨论】:

    【解决方案2】:

    我猜您正在测试的机器具有不同的框架版本,并且由于 .NET 4.5 中的这一新功能,您遇到了不兼容问题:http://msdn.microsoft.com/en-us/library/bb613588%28v=VS.110%29.aspx#static_properties

    【讨论】:

    • 4.5 是 CLR 的就地升级,因此即使在安装了 4.5 的计算机上运行 4.0 应用程序也会针对 4.5 CLR 运行,并且行为可能略有不同。不确定这是否是您的问题,但它应该是您检查的第一件事。
    猜你喜欢
    • 1970-01-01
    • 2018-09-19
    • 2012-04-14
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多