x:Key和x之间的区别:名称

Jea*_*ert 9 silverlight wpf

x:Key和x:WPF中的名称有什么区别?

Leo*_*rke 12

x:密钥仅在资源字典中有效并添加到字典中,x:名称在本地使用,表示类中的变量.


Ste*_*rex 8

x:Name用于命名UI元素(例如控件,面板等),而x:Key用于标识a中的资源(可以是或多或少的任何东西)ResourceDictionary.

这意味着您无法使用x:Name值引用资源字典中的内容:

 <Grid>
    <Grid.Resources>
        <Style x:Name="StyleName" x:Key="StyleKey" />
    </Grid.Resources>
    <Button Style="{StaticResource StyleName}" /> <!-- Will not work-->
    <Button Style="{StaticResource StyleKey}" /> <!-- Will work -->
</Grid>
Run Code Online (Sandbox Code Playgroud)

您还会注意到不在资源字典中的元素不能具有以下x:Key属性:

<TextBox x:Key="TextBoxKey" /> <!-- Will not compile -->
Run Code Online (Sandbox Code Playgroud)