本文是小编为大家收集整理的关于WPF的一个小问题的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。
问题描述
您好,WPF 专家:
<文本框 x:name="textBox1">一些文本</文本框>
这里的"x:"是什么意思,为什么我们需要它?
谢谢!
推荐答案
来自 文档[^]
为处理对象元素后存在于运行时代码中的实例指定运行时对象名称
参见:
http://social.msdn.microsoft.com/论坛/da-DK/wpf/thread/216553bf-9be2-4d0a-acc1-b38af8ef948e[^]引用:如果是"Key"而不是"x:Key",这将要求"Key"是
作为资源添加的"元素",根据 XAML 甚至 XML 的语法规则.
在 WPF 中,这意味着每个对象都作为资源添加
需要公开一个名为"Key"的可写 DependencyProperty.
这将排除所有不是 DependencyObjects 的类型 - 例如字符串或 URI 或
ViewModels 实例 - 以及所有没有名为"Key"的 DP 的实例,
所以只是所有常用作为资源的对象!
使用 "x:Key" 指令的实现,键不需要是
的真正属性添加的元素,您可以将其视为元素的"附加"属性(只是寓言
在技术上不是 AttachedProperty).
请注意,如果一个类型具有由 DictionaryKeyPropertyAttribute 标记的属性,那么您
实际上不需要"x:Key",而是可以使用该类型的"Key"属性(可能有不同的名称)——就像你建议的那样.
请注意,"x:Name"和"Name"的关系与"x:Key"和"Key"的关系大致相同.
如果您使用"Name",则该元素需要公开一个名为"Name"的可写 DP,
与"Key"相反,最常见的情况是-因为"Name"是
的DP每个 FrameworkElement 和 FrameworkContentElement,因此 >90% 的元素用于 XAML,
这就是为什么 Name 和 x:Name 经常作为同义词出现并且可以互换
(它们不完全)但 "x:Key" 和 "Key" 没有.
这同样适用于 XAML 中的所有 x: 属性
问题描述
Hi, WPF experts:
<textbox x:name="textBox1"> some text</textbox>
what does it mean here "x:", why we need it here?
thanks!
推荐答案
From the documentation[^]
Specifies a run-time object name for the instance that exists in run-time code after an object element is processed
See this:
http://social.msdn.microsoft.com/Forums/da-DK/wpf/thread/216553bf-9be2-4d0a-acc1-b38af8ef948e[^]
Quote:If it was "Key" rather than "x:Key" this would require "Key" to be an "attribute" of
the "element" added as a resource, according to the syntax rules of XAML and even XML.
In WPF this would mean that every object added as a resource
would need to expose a writable DependencyProperty named "Key".
This would rule out all types that are not DependencyObjects - such as strings or URIs or
ViewModels instances - and more over all those that don''t have such DP named "Key",
so merely all objects commonly used as resources!
With the implementation as "x:Key" directive the key doesn''t need to be a true attribute of
the element added, you can look it as kind of an "attached" attribute to the element (just allegorically
not technically an AttachedProperty).
Note that if a type has a property marked by the DictionaryKeyPropertyAttribute then you
actually don''t need the "x:Key" but may rather use the "Key" property of that type (which may have a different name) - just the way you proposed.
Note that for "x:Name" and "Name" the relation is about the same as for "x:Key" and "Key".
If you use "Name" the element needs to expose a writable DP named "Name",
which in contrast to "Key" is most often the case - because "Name" is a DP of
every FrameworkElement and FrameworkContentElement, so >90% of elements used in XAML,
so that''s why Name and x:Name often appear as synonyms and mutually interchangeable
(which they are not fully) but "x:Key" and "Key" do not.
The same applies to all x: attributtes in XAML
相关标签/搜索