绑定源与x:静态 [英] Binding Source vs x:Static

查看:70
本文介绍了绑定源与x:静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以绑定到静态属性.现在,我知道执行此操作的2种方法:

in WPF one can bind to static properties. Now I know 2 ways of doing this:

Content="{x:Static stat:Statics.CurrentUser}"

或者:

Content="{Binding Source={x:Static stat:Statics.CurrentUser}}"

这两种方法之间有什么区别吗?

Are there any differences between these 2 methods?

推荐答案

在这种情况下,主要区别在于x:Static不执行其他转换

Main difference in this case is that x:Static does not perform additional conversion

来自 x:Static Markup Extension

在进行x:Static引用而不直接是属性值的类型时,请格外小心.在XAML处理序列中,标记扩展提供的值不会调用其他值转换.即使您的x:Static引用创建了文本字符串,也是如此,并且对于该特定成员或返回类型的任何成员值,通常都会基于文本字符串对属性值进行值转换.

Use caution when you make x:Static references that are not directly the type of a property's value. In the XAML processing sequence, provided values from a markup extension do not invoke additional value conversion. This is true even if your x:Static reference creates a text string, and a value conversion for attribute values based on text string typically occurs either for that specific member or for any member values of the return type.

所以可以这样说

<TextBlock Text="{x:Static SystemColors.ActiveBorderBrush}"/>

这将导致运行时错误:

#FFB4B4B4"不是属性文本"的有效值.

'#FFB4B4B4' is not a valid value for property 'Text'.

因为SolidColorBrush不是String

<TextBlock Text="{Binding Source={x:Static SystemColors.ActiveBorderBrush}}"/>

可以正常工作并显示#FFB4B4B4 ,因为它将执行ToString()转换.同样,如果没有Binding,您将无法访问静态对象的实例属性,因此,例如,您将无法获得该笔刷的Color属性.

will work fine and display #FFB4B4B4 because it will perform ToString() conversion. Also without Binding you are not able to access instance properties of static object so for example you would not be able to get Color property of that brush

<TextBlock Text="{Binding Source={x:Static SystemColors.ActiveBorderBrush}, Path=Color}"/>

这篇关于绑定源与x:静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆