简体   繁体   English

值转换器vs附加属性

[英]Value converter vs Attached property

In case of long lines in xaml with bool to visibility converters I find this question interesting. 如果在xaml中使用bool到可见性转换器的长行,我发现这个问题很有趣。 What will do the job better: value converter or attached property? 什么能做得更好:价值转换器或附加财产?

Using value converter from bool to Visibility: 使用从bool到可见性的值转换器:

Visibility="{Binding IsCommentPreviewVisible,Converter={StaticResource myBoolToVisibilityConverter}}" 

or using attached property: 或使用附属物:

ap:BoolVisibility.Visible="{Binding IsCommentPreviewVisible}"

where VisibleChanged internally handle Visibility of FrameworkElement . VisibleChanged内部处理FrameworkElement Visibility

Custom attached properties are generally good for when you need to set a property for a class other than the defining class. 当您需要为定义类以外的类设置属性时,自定义附加属性通常很有用。

Take Canvas.Left , Canvas.Top , Canvas.Right , Canvas.Bottom for example, these properties are for the parent element to use, not specifically for the defining element. Canvas.LeftCanvas.TopCanvas.RightCanvas.Bottom为例,这些属性用于元素,而不是专门用于定义元素。 You would use Canvas. 你会使用Canvas. attached properties to define the positioning of elements within another element (a Canvas ). 附加属性来定义另一元件(一个元件的定位Canvas )。

It might be worth reading the documentation . 可能值得阅读文档

Converters on the other hand offer you the means of quite simply, converting one data type to another on the UI. 另一方面,转换器为您提供了非常简单的方法,在UI上将一种数据类型转换为另一种数据类型。 That being said, you can still use an attached property to mimic the behaviour of a converter. 话虽这么说,你仍然可以使用附加属性来模仿转换器的行为。

If you need to do anything culture aware then an IValueConverter has this built in, an attached property does not. 如果你需要做任何文化意识的事情,那么IValueConverter内置了这个,附加属性没有。 See the documentation 请参阅文档

Personally I tend to steer away from attached properties unless I need to attach a property which a parent class will need to use. 我个人倾向于避开附加属性,除非我需要附加父类需要使用的属性。 It's difficult to provide a real example because I rarely use them, if ever. 很难提供一个真实的例子,因为我很少使用它们,如果有的话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM