gpt4 book ai didi

c# - 我如何添加自定义属性,如 x :Name ="value"?

转载 作者:太空宇宙 更新时间:2023-11-03 13:23:15 25 4
gpt4 key购买 nike

大家好,我厌倦了在 xaml 中为所有控件创建自定义属性

// ... 
<TextBlock x:Name="tblck1"/>
//...

我想像这样创建我的:

//...
<TextBlock g:Language="EN"/>
//...

我厌倦了静态类和 MarkupExtension,但它似乎不是正确的方法!请帮我。提前致谢。

最佳答案

首先,我不明白为什么要自定义前缀 g: 来定义 Language 属性。你有两种选择来实现你想要的。

依赖属性 来自 msdn

The purpose of dependency properties is to provide a way to compute the value of a property based on the value of other inputs. These other inputs might include system properties such as themes and user preference, just-in-time property determination mechanisms such as data binding and animations/storyboards, multiple-use templates such as resources and styles, or values known through parent-child relationships with other elements in the element tree

附加属性 来自 msdn

An attached property is a concept defined by XAML. An attached property is intended to be used as a type of global property that is settable on any object. In Windows Presentation Foundation (WPF), attached properties are typically defined as a specialized form of dependency property that does not have the conventional property "wrapper".

你指定你想要这样的东西

<TextBlock g:Language="EN"/>

如果你想让它看起来像这样

<TextBlock Language="EN"/>

那么您别无选择,只能创建一个派生自 TextBlock 的自定义控件并创建一个 Dependency 属性

所以它最终会变成这样

 <controls:CustomTextBlock Language="EN"/>

您的另一个选择是创建一个附加属性,它最终看起来像

<TextBlock attachProperties:ClassToDefineAttachProperty.Language="EN"/>

选择权在你。

我宁愿使用附加属性,因为在遇到诸如拥有Language 属性等问题时,扩展任何现有类会更容易。

关于c# - 我如何添加自定义属性,如 x :Name ="value"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23394015/

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