In WPF, what are the differences between the x:Name and Name attributes?

前端 未结 15 1552
闹比i
闹比i 2020-11-22 05:19

The title says it all. Sometimes it seems that the Name and x:Name attributes are interchangeable.

So, what are the definitive differences

15条回答
  •  Happy的楠姐
    2020-11-22 05:46

    They're both the same thing, a lot of framework elements expose a name property themselves, but for those that don't you can use x:name - I usually just stick with x:name because it works for everything.

    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.

提交回复
热议问题