IT박스

WPF에서 x : Name 및 Name 특성의 차이점은 무엇입니까?

itboxs 2020. 10. 4. 10:44
반응형

WPF에서 x : Name 및 Name 특성의 차이점은 무엇입니까?


제목에 모든 것이 나와 있습니다. 때때로 Namex:Name속성은 서로 바꿔서 사용할 수있는 것처럼 보입니다 .

그렇다면 그들 사이의 결정적인 차이점은 무엇이며 언제 다른 것을 사용하는 것이 더 좋을까요?

잘못된 방법으로 사용하면 성능이나 메모리에 영향이 있습니까?


XAML에는 실제로 x:Name. WPF와 같은 프레임 워크 는 클래스 속성 중 하나를 XAML의 x : Name 특성에 대한 매핑으로 지정하는 클래스 에서을 x:Name사용하여 해당 속성 중 하나를 XAML에 선택적으로 매핑 할 수 있습니다 RuntimeNamePropertyAttribute.

이 작업을 수행 한 이유는 WPF와 같이 런타임에 이미 "이름"개념이있는 프레임 워크를 허용하기 위해서입니다. 예를 들어 WPF에서는 FrameworkElementName 속성을 도입합니다.

일반적으로 클래스는 x:Name사용할 수 있도록 이름을 저장할 필요가 없습니다 . x:NameXAML의 모든 의미는 클래스 뒤에있는 코드에 값을 저장하는 필드를 생성하는 것입니다. 런타임이 해당 매핑으로 수행하는 작업은 프레임 워크에 따라 다릅니다.

그렇다면 동일한 작업을 수행하는 두 가지 방법이있는 이유는 무엇입니까? 간단한 대답은 하나의 속성에 두 개의 개념이 매핑되어 있기 때문입니다. WPF는 런타임시 보존되는 요소의 이름 (특히 Bind를 통해 사용할 수 있음)을 원하며 XAML은 클래스 뒤에있는 코드의 필드에서 액세스 할 수있는 요소를 알아야합니다. WPF는 Name 속성을 x : Name의 별칭으로 표시하여이 두 가지를 함께 연결합니다.

앞으로 XAML은 이름으로 다른 개체를 참조하여 속성을 설정할 수 있도록하는 등 x : Name에 더 많이 사용되지만 3.5 이전 버전에서는 필드를 만드는 데만 사용됩니다.

둘 중 하나를 사용해야하는지 여부는 기술적 인 문제가 아니라 스타일 문제입니다. 추천을 위해 다른 사람에게 맡기겠습니다.

도 참조 AutomationProperties.Name VS는 X : 이름 , AutomationProperties.Name은 접근성 도구와 몇 가지 테스트 도구에 의해 사용된다.


그들은 같은 것이 아닙니다.

x:Name주로 요소를 참조하는 데 사용되는 xaml 개념입니다. 요소에 x : Name xaml 속성을 부여하면 "지정된 항목 x:Name은 xaml이 처리 될 때 기본 코드에서 생성되는 필드의 이름이되며 해당 필드는 객체에 대한 참조를 보유합니다." ( MSDN ) 따라서 기본적으로 내부 액세스 권한이있는 디자이너 생성 필드입니다.

Name는의 기존 문자열 속성으로 FrameworkElement, xaml 속성 형식의 다른 wpf 요소 속성으로 나열됩니다.

결과적으로 이것은 또한 x:Name더 넓은 범위의 물체에서 사용될 수 있음을 의미 합니다. 이것은 xaml의 모든 항목을 지정된 이름으로 참조 할 수있는 기술입니다.


x : Name 및 Name은 서로 다른 네임 스페이스를 참조합니다.

x : name 은 기본적으로 Xaml 파일의 맨 위에 정의 된 x 네임 스페이스에 대한 참조입니다.

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Name 이라고 말하면 아래의 기본 네임 스페이스를 사용합니다.

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

x : Namex 별칭 이있는 네임 스페이스를 사용한다고 말합니다 . x는 기본값이며 대부분의 사람들은 그대로 두지 만 원하는대로 변경할 수 있습니다.

xmlns:foo="http://schemas.microsoft.com/winfx/2006/xaml"

그래서 당신의 참조는 foo : name

WPF에서 네임 스페이스 정의 및 사용


좋습니다. 이것을 다른 방식으로 살펴 보겠습니다. 버튼을 Xaml 페이지로 드래그 앤 드롭한다고 가정 해 보겠습니다. 이 두 가지 방법으로 x : namename을 참조 할 수 있습니다 . 모든 xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns : x = "http://schemas.microsoft.com/winfx/2006/xaml" 은 여러 네임 스페이스에 대한 참조입니다. . 이후 XAML은 보류를 제어 (즉에 대한 100 %) 네임 스페이스를하고 발표는 보류를 FrameworkElement을 하고 버튼 클래스 의 상속 패턴을 가지고 :

Button : ButtonBase
ButtonBase : ContentControl, ICommandSource
ContentControl : Control, IAddChild
Control : FrameworkElement
FrameworkElement : UIElement, IFrameworkInputElement, 
                    IInputElement, ISupportInitialize, IHaveResources

따라서 FrameworkElement에서 상속 된 모든 것은 모든 공용 속성에 액세스 할 수 있습니다. 따라서 Button의 경우 계층 구조 트리의 맨 위에있는 FrameworkElement에서 Name 특성을 가져옵니다. 따라서 x : Name 또는 Name 이라고 말하면 둘 다 FrameworkElement에서 getter / setter에 액세스하게됩니다.

MSDN 참조

WPF는 여러 CLR 네임 스페이스를 단일 XML 네임 스페이스에 매핑하기 위해 XAML 프로세서에서 사용하는 CLR 특성을 정의합니다. XmlnsDefinitionAttribute의 속성은 어셈블리를 생성하는 소스 코드 어셈블리 레벨에 배치된다. WPF 어셈블리 소스 코드는이 특성을 사용하여 System.Windows 및 System.Windows.Controls와 같은 다양한 공통 네임 스페이스를 http://schemas.microsoft.com/winfx/2006/xaml/presentation 네임 스페이스 에 매핑합니다 .

따라서 어셈블리 속성은 다음과 같습니다.

PresentationFramework.dll-XmlnsDefinitionAttribute :

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Data")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Navigation")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Shapes")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Documents")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Controls")]  

둘 다 똑같습니다. 많은 프레임 워크 요소가 자체적으로 이름 속성을 노출하지만, 그렇지 않은 경우에는 x : name을 사용할 수 있습니다. 일반적으로 x : name 만 사용합니다.

Controls can expose name themselves as a Dependency Property if they want to (because they need to use that Dependency Property internally), or they can choose not to.

More details in msdn here and here:

Some WPF framework-level applications might be able to avoid any use of the x:Name attribute, because the Name dependency property as specified within the WPF namespace for several of the important base classes such as FrameworkElement/FrameworkContentElement satisfies this same purpose. There are still some common XAML and framework scenarios where code access to an element with no Name property is necessary, most notably in certain animation and storyboard support classes. For instance, you should specify x:Name on timelines and transforms created in XAML, if you intend to reference them from code.

If Name is available as a property on the class, Name and x:Name can be used interchangeably as attributes, but an error will result if both are specified on the same element.


X:Name can cause memory issues if you have custom controls. It will keep a memory location for the NameScope entry.

I say never use x:Name unless you have to.


The only difference is that if you are using user Controls into a control from Same Assembly then Name will not identify your control and you will get an error " Use x:Name for controls in the same Assembly". So x:Name is the WPF versioning of naming controls in WPF. Name is just used as a Winform Legacy. They wanted to differentiate the naming of controls in WPF and winforms as they use attributes in Xaml to identify controls from other assemblies they used x: for Names of control.

Just keep in mind dont put a name for a control just for the sake of keeping it as it resides in memory as a blank and it will give you a warning that Name has been applied for a control buts its never used.


Name:

  1. can be used only for descendants of FrameworkElement and FrameworkContentElement;
  2. can be set from code-behind via SetValue() and property-like.

x:Name:

  1. can be used for almost all XAML elements;
  2. can NOT be set from code-behind via SetValue(); it can only be set using attribute syntax on objects because it is a directive.

Using both directives in XAML for one FrameworkElement or FrameworkContentElement will cause an exception: if the XAML is markup compiled, the exception will occur on the markup compile, otherwise it occurs on load.


x:Name means: create a field in the code behind to hold a reference to this object.

Name means: set the name property of this object.


I always use the x:Name variant. I have no idea if this affects any performance, I just find it easier for the following reason. If you have your own usercontrols that reside in another assembly just the "Name" property won't always suffice. This makes it easier to just stick too the x:Name property.


It's not a WPF item but a standard XML one and BtBh has correctly answered it, x refers to the default namespace. In XML when you do not prefix an element/attribute with a namespace it assumes you want the default namespace. So typing just Name is nothing more than a short hand for x:Name. More details on XML namespaces can be found at link text


One of the answers is that x:name is to be used inside different program languages such as c# and name is to be used for the framework. Honestly that is what it sounds like to me.


When you declare a Button element in XAML you are referring to a class defined in windows run time called Button.

Button has many attribute such as background, text, margin, ..... and an attribute called Name.

Now when you declare a Button in XAML is like creating an anonymous object that happened to have an attribute called Name.

In general you can not refer to an anonymous object, but in WPF framework XAML processor enables you to refer to that object by whatever value you have given to Name attribute.

So far so good.

Another way to create an object is create a named object instead of anonymous object. In this case XAML namespace has an attribute for an object called Name (and since it is in XAML name space thus have X:) that you may set so you can identify your object and refer to it.

Conclusion:

Name is an attribute of a specific object, but X:Name is one attribute of that object (there is a class that defines a general object).


The specified x:Name becomes the name of a field that is created in the underlying code when XAML is processed, and that field holds a reference to the object. In Silverlight, using the managed API, the process of creating this field is performed by the MSBuild target steps, which also are responsible for joining the partial classes for a XAML file and its code-behind. This behavior is not necessarily XAML-language specified; it is the particular implementation that Silverlight applies to use x:Name in its programming and application models.

Read More on MSDN...


My research is x:Name as global variable. However, Name as local variable. Does that mean x:Name you can call it anywhere in your XAML file but Name is not.
Example:

<StackPanel>
<TextBlock Text="{Binding Path=Content, ElementName=btn}" />
<Button Content="Example" Name="btn" />
</StackPanel>
<TextBlock Text="{Binding Path=Content, ElementName=btn}" />

You can't Binding property Content of Button with Name is "btn" because it outside StackPanel

참고URL : https://stackoverflow.com/questions/589874/in-wpf-what-are-the-differences-between-the-xname-and-name-attributes

반응형