What's the difference between x:Key and x:Name in WPF?

前端 未结 2 1649
梦谈多话
梦谈多话 2020-12-15 02:32

What\'s the difference between x:Key and x:Name in WPF?

I am not sure what the true difference is.

2条回答
  •  醉话见心
    2020-12-15 02:58

    Although they are used for similar purposes, they are not interchangeable. x:Key is used for items that are being added as values to a dictionary, most often for styles and other resources that are being added to a ResourceDictionary. When setting the x:Key attribute, there is actually no corresponding property on the object or even an attached dependency property being set. It is simply used by the XAML processor to know what key to use when calling Dictionary.Add.

    x:Name is a bit more complicated. It's used to apply an associated name to an object (typically an object derived from FrameworkElement) within the scope of some parent element. This scope is called a "namescope" and the easiest way to think of it is to imagine a UserControl that contains a .

    You could then put multiple instances of the UserControl onto a Window without the name "foo" colliding because each UserControl has its own namescope.

    It's worth noting too that FrameworkElement defines a dependency property called Name that is equivalent to setting x:Name.

    The other difference is that the XAML designer creates members in the code-behind for elements that have an x:Name. This is not true of objects added to a dictionary using x:Key.

    You can find more information about these in the remarks section of the MSDN documentation for the x:Name directive.

提交回复
热议问题