Binding to static class property

吃可爱长大的小学妹 提交于 2019-12-17 05:01:17

问题


I want to bind a textblock text to a property of a static class. Whenever the property value of the static class changes, it should reflect to the textblock which is on the other window or custom control.


回答1:


You can bind to ANY property on a static class using the x:Static markup extension but if thy do not implement any change tracking, it might cause errors on the refresh!

<TextBlock Text="{Binding Source={x:Static sys:Environment.MachineName}}" />



回答2:


This has worked for me:

Text="{Binding Source={x:Static MyNamespace:MyStaticClass.MyProperty}, Mode=OneWay}"

Without Mode=OneWay I got an exception.




回答3:


For those who use nested static classes to organize/seperate constants. If you need to Bind into nested static classes, It seems you need to use a plus (+) operator instead of the dot (.) operator to access the nested class:

{Binding Source={x:Static namespace:StaticClass+NestedStaticClasses.StaticVar}}

Example:

public static class StaticClass
    {
        public static class NestedStaticClasses
        {
            public static readonly int StaticVar= 0;

        }
    }


来源:https://stackoverflow.com/questions/3862455/binding-to-static-class-property

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