wpf - 将datacontext绑定到singleton类的静态属性

时间:2010-10-25 20:15:36

标签: c# .net wpf binding

我发现自己使用了很多单独的绑定到我的App类来存储属性,这导致了一个无法解决的stackoverflow异常。我现在决定将这些属性移动到单独的单例ApplicationInfo类中,但是我遇到了一些绑定问题。

如果我直接绑定到我的类的成员属性,例如CurrentUser,那么它可以正常工作。但是当我尝试将datacontext绑定到这个类时,我遇到编译器错误,我确信有一些我忽略的简单修改。

我已经从这个类中创建了一个单例,但是现在当我尝试编译时,我得到错误“Unknown build error - key not not null”,它指向我的Datacontext绑定以获取错误消息。

这是我的班级:

 public class ApplicationInfo
{
    private ApplicationInfo()
    {

    }
    private static ApplicationInfo _Current = new ApplicationInfo();
    public static  ApplicationInfo Current
    {
        get { return _Current; }         
    }

    #region Application Info Properties
    private static Assembly _ExecutingAssembly = System.Reflection.Assembly.GetExecutingAssembly();  //holds a copy of this app's assembly info
    public static String ApplicationName
    {
        get { return _ExecutingAssembly.ManifestModule.Name; }
    }
    public static String ApplicationNameTrimmed
    {
        get { return _ExecutingAssembly.ManifestModule.Name.TrimEnd('.', 'e', 'x'); }
    }
    public static String ApplicationPath
    {
        get { return _ExecutingAssembly.Location; }
    }
    public static String ApplicationVersion
    {
        get { return _ExecutingAssembly.GetName().Version.ToString(); }
    }
    public static DateTime ApplicationCompileDate
    {
        get { return File.GetCreationTime(Assembly.GetExecutingAssembly().Location); }
    }
    #endregion
    private static Boolean _hasOpenWindows;
    public static Boolean HasOpenWindows
    {
        get { return _hasOpenWindows; }
        set { _hasOpenWindows = value; }
    }

    private static User _currentuser;
    public static User CurrentUser
    {
        get { return _currentuser; }
        set { _currentuser = value; }
    }
    private static Mantissa.DAL _datalayer;
    public static Mantissa.DAL DataLayer
    {
        get { return _datalayer; }
        set { _datalayer = value; }
    }
    private static string _connectionstring;
    public static string ConnectionString
    {
        get { return _connectionstring; }
        set { _connectionstring = value; }
    }





}

这有效:

`Title="{Binding Source={x:Static my:ApplicationInfo.ApplicationNameTrimmed}}"`

这不会:(抛出密钥不能为null msg)

DataContext="{Binding Source={x:Static my:ApplicationInfo.Current}}"

但是当我在我的App类中放置相同的属性时,这可以工作:

  DataContext="{Binding Source={x:Static Application.Current}}"

所以我该如何解决这个问题呢?

1 个答案:

答案 0 :(得分:11)

x:Static用于获取静态字段和属性。 ApplicationInfo是一个类,而不是属性。要绑定,您必须创建它的实例并使用其实例属性,或绑定到静态属性(访问它不需要实例)。

如果要绑定到特定属性,请使用Title="{Binding Source={x:Static my:ApplicationInfo.ApplicationNameTrimmed}}"

如果要设置DataContext然后使用绑定到其他属性,请使用DataContext="{Binding Source={x:Static my:ApplicationInfo.Current}}"并将静态属性转换为实例属性(删除静态关键字)。你也可以像这样绑定:Title="{Binding Source={x:Static my:ApplicationInfo.Current.ApplicationNameTrimmed}}"

相关问题