一切都在标题中:
我不止一次读过设置这样的样式:
<Style TargetType="TextBox">...</Style>
Run Code Online (Sandbox Code Playgroud)
大致相当于:
<Style x:Key="{x:Type TextBox}" TargetType="TextBox">...</Style>
Run Code Online (Sandbox Code Playgroud)
(最后一次评论另一个问题)
两者都应该将样式应用于应用程序中的所有textBox(如果它们当然放在应用程序的资源中)
但是我在我的应用程序中都试过了,只有第二个用x:Key定义了.
它对我来说非常合乎逻辑,因为第一个不知道在没有任何x:Key属性集的情况下应用的位置,但那么第一个语法的重点是什么?
编辑:我的应用程序中的代码示例工作正常:
<Style x:Key="{x:Type ComboBoxItem}" TargetType="{x:Type ComboBoxItem}">
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
</Style>
Run Code Online (Sandbox Code Playgroud)
和代码不:
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
</Style>
Run Code Online (Sandbox Code Playgroud)
我写这个是为了摆脱你操纵现有ComboBox的itemsSource时用comboBoxItems得到的绑定问题.第一个代码工作正常,但第二个代码没有.
通过将horizontalContentAlignment设置为Right,您可以轻松地看到这一点
编辑2:这段代码只是放在App.xaml的资源字典中.用TargetType ="ComboBoxItem"替换TargetType ="{x:Type ComboBoxItem}"没有任何区别
编辑3:我刚刚意识到我可能忘记了确切的重要事项(对不起):尽管样式是在xaml中定义的,但我实际上是在我的代码中将控件添加到布局中,因为它们是动态添加的.可能是麻烦所在......
H.B*_*.B. 10
如上面的第一个示例所示,将TargetType属性设置为TextBlock而不使用x:Key指定样式允许将样式应用于所有TextBlock元素.实际发生的是,这样做会隐式地将x:Key设置为{x:Type TextBlock}.这也意味着如果您为Style赋予除{x:Type TextBlock}以外的任何内容的x:Key值,则Style将不会自动应用于所有TextBlock元素.相反,您需要显式地将样式应用于TextBlock元素.
考虑到这是来自官方文档,您的问题必须是异常.我已经看到了一些这样的奇怪之处,因为WPF背后的编码肯定是不完美的,所以它们并不是太出乎意料.
(是否有结果之间的差异TargetType="ComboBoxItem"
和TargetType="{x:Type ComboBoxItem}"
如果省略了钥匙?)
现在您可以通过添加以下内容来级联您的样式:
BasedOn="{StaticResource {x:Type ComboBox}}"
Run Code Online (Sandbox Code Playgroud)
在文档下方的 <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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9725 次 |
最近记录: |