首页 文章

x:Key =“{x:Type TextBox}”是做什么的?

提问于
浏览
13

一切都在 Headers 中:

我不止一次读过设置这样的样式:

<Style TargetType="TextBox">...</Style>

大致相当于:

<Style x:Key="{x:Type TextBox}" TargetType="TextBox">...</Style>

(上次in a comment on another question

两者都应该将样式应用于应用程序中的所有textBox(如果它们当然放在应用程序的资源中)

但是我在我的应用程序中都试过了,只有第二个用x:Key定义了 .

它对我来说非常合乎逻辑,因为第一个不知道在没有任何x:Key属性集的情况下应用到哪里,但那么第一个语法的重点是什么?

Edit: 我的应用程序中的代码示例正常工作:

<Style x:Key="{x:Type ComboBoxItem}" TargetType="{x:Type ComboBoxItem}">
     <Setter Property="HorizontalContentAlignment" Value="Left"/>
     <Setter Property="VerticalContentAlignment" Value="Center"/>
</Style>

和代码不:

<Style TargetType="{x:Type ComboBoxItem}">
     <Setter Property="HorizontalContentAlignment" Value="Left"/>
     <Setter Property="VerticalContentAlignment" Value="Center"/>
</Style>

我写这个是为了摆脱你操纵现有ComboBox的itemsSource时用comboBoxItems得到的绑定问题 . 第一个代码工作正常,但第二个代码没有 .

通过将horizontalContentAlignment设置为Right,您可以轻松地看到这一点

Edit 2: 此代码只是放在App.xaml的资源字典中 . 用TargetType = "ComboBoxItem"替换TargetType = ""没有任何区别

Edit 3: 我刚刚意识到我可能已经忘记了确切的重要事项(抱歉):虽然样式是在xaml中定义的,但实际上我在代码后面的布局中添加了控件,因为它们是动态添加的 . 可能是麻烦所在......

3 回答

  • 2

    如上面的第一个示例所示,将TargetType属性设置为TextBlock而不使用x:Key指定样式允许将样式应用于所有TextBlock元素 . 实际发生的是,这样做会隐式地将x:Key设置为{x:Type TextBlock} . 这也意味着如果您为Style赋予除{x:Type TextBlock}之外的任何内容的x:Key值,则Style将不会自动应用于所有TextBlock元素 . 相反,您需要显式地将样式应用于TextBlock元素 .

    考虑到这是from the official documentation,您的问题必须是异常 . 我已经看到了一些这样的奇怪之处,因为WPF背后的编码必然是不完美的,所以它们并不太令人意外 .

    (如果省略键, TargetType="ComboBoxItem"TargetType="{x:Type ComboBoxItem}" 之间的结果是否有差异?)

  • 4

    现在,您可以通过添加以下内容来级联样式:

    BasedOn="{StaticResource {x:Type ComboBox}}"
    

    在文档中的<Style />中,例如:

    <Window.Resources>
         <Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">
              <Setter Property="HorizontalContentAlignment" Value="Left"/>
              <Setter Property="VerticalContentAlignment" Value="Center"/>
          </Style>
    </Window.Resources>
    <StackPanel>
        <TextBox>I'm Left-Center</TextBox>
        <Grid>
            <Grid.Resources>
               <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
                    <Setter Property="HorizontalContentAlignment" Value="Right"/>
                </Style>
            <Grid.Resources>
            <TextBox>I'm Right-Center</TextBox>
        </Grid>
    </StackPanel>
    
  • 9

    每个资源都需要一个键,但如果样式省略了 Key ,则它应该默认为 TargetType 的类型 . 因此,上面的两个片段都应该是等效的 .

    如果没有明确的 Key 定义,您可以将整个代码发布到不起作用的地方吗?

相关问题