Can I set a DataContext to a static class?

浪子不回头ぞ 提交于 2019-12-09 00:34:22

问题


I've a static class which reads information from the application assembly.

I've declared it static since the class needs no instance declaration and will only ever be read directly from, application-wide. I have a control with several labels that I would like to use to display some of this information.

How can I go about setting the controls DataContext equal to the class?

Code:

/// <summary>
/// Class for Reading Program Information.
/// </summary>
public static class ProgramInfo {
    private static Assembly ProgramAssembly = Assembly.GetEntryAssembly( );

    /// <summary>
    /// Get Program Name
    /// </summary>
    public static string ProgramName {
        get { return ProgramInfo.ProgramAssembly.GetCustomAttribute<AssemblyProductAttribute>( ).Product; }
    }

    /// <summary>
    /// Get Program Build Date
    /// </summary>
    public static DateTime BuildDate {
        get { return File.GetLastWriteTime( ProgramInfo.ProgramAssembly.Location ); }
    }

    /// <summary>
    /// Get Program Version (Major.Minor)
    /// </summary>
    public static string Version {
        get {
            System.Version V = ProgramInfo.ProgramAssembly.GetName( ).Version;
            return V.Major.ToString( ) + '.' + V.Minor.ToString( );
        }
    }

    /// <summary>
    /// Get Program Build (Build.Revision)
    /// </summary>
    public static string Build {
        get {
            System.Version V = ProgramInfo.ProgramAssembly.GetName( ).Version;
            return V.Build.ToString( ) + '.' + V.Revision.ToString( );
        }
    }
}

XAML:

<UserControl x:Class="Tools.Controls.ProgramInformation"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:pi="clr-namespace:Tools.Controls">
<UserControl.DataContext>
    <pi:ProgramInfo/>
</UserControl.DataContext>
<!--Other Irrelevant Code-->
</UserControl>

回答1:


You can bind to a static field or property by using the {x:Static} binding syntax.

x:Static is used to get static fields and properties. You can set the datacontext to a static field, or property, but not to a static type.

Example below:

<DataContext Source="{x:Static prefix:typeName.staticMemberName}" />

It'd be more appropriate for you to ignore the datacontext, and just use a {x:Static binding for each value you wish to bind. For example, below would bind the program name static property:

<TextBlock Text="{Binding Source={x:Static pi:ProgramInfo.ProgramName}}" /> 
|improve this answer

来源:https://stackoverflow.com/questions/27880492/can-i-set-a-datacontext-to-a-static-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!