gpt4 book ai didi

wpf - 绑定(bind)源 vs x :Static

转载 作者:行者123 更新时间:2023-12-03 22:48:00 24 4
gpt4 key购买 nike

在 WPF 中,可以绑定(bind)到静态属性。现在我知道了两种方法:

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

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

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

最佳答案

这种情况下的主要区别在于 x:Static不执行额外的转换

来自 x:Static Markup Extension

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' is not a valid value for property 'Text'.



因为 SolidColorBrush不是 String同时
<TextBlock Text="{Binding Source={x:Static SystemColors.ActiveBorderBrush}}"/>

可以正常工作并显示#FFB4B4B4,因为它将执行 ToString()转换。也没有 Binding您无法访问静态对象的实例属性,例如您将无法获得 Color那把刷子的属性
<TextBlock Text="{Binding Source={x:Static SystemColors.ActiveBorderBrush}, Path=Color}"/>

关于wpf - 绑定(bind)源 vs x :Static,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24221001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com