【发布时间】:2012-06-13 09:09:34
【问题描述】:
几天前,我遇到了 Button 中文本的奇怪行为(我猜其他 ContentControl 也会遇到同样的行为)。让我解释一下情况。我在 App.xaml 中有一个 TextBlock 的样式定义:
<Application.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Margin" Value="10"/>
</Style>
</Application.Resources>
在 MainWindow.xaml 中我有相同的样式定义,它应该覆盖在 App.xaml 中定义的样式。我在 Window 中也有 3 个按钮。在第一个按钮中,在按钮内容中明确定义了 TextBlock 控件。对于第二个按钮,我将字符串设置为代码隐藏中的内容。对于第三个按钮,我将一个整数值设置为代码隐藏中的内容。这是 MainWindow.xaml 的代码:
<StackPanel>
<StackPanel.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Margin" Value="0"/>
</Style>
</StackPanel.Resources>
<Button Name="Button1">
<Button.Content>
<TextBlock Text="Button with text block"/>
</Button.Content>
</Button>
<Button Name="Button2" />
<Button Name="Button3" />
</StackPanel>
和 MainWindow.xaml.cs:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Button2.Content = "Button with string";
Button3.Content = 16;
}
现在我们看到了什么?正如预期的那样,第一个和第三个按钮中的文本有 0 像素的边距,但第二个按钮中的文本有 10 像素的边距!问题是:为什么第二个按钮有 10px 的边距以及如何为第二个按钮设置零边距(从 App.xaml 中删除样式是不可能的)?
谢谢!
【问题讨论】:
-
snoop 揭示了什么?
-
我已经尝试过您的代码:Snoop 说第二个 TextBlock 的 Margin=10,而其他 TextBlock 的 Margin=0。在所有三种情况下,值源都是一种样式。目前,我不知道是什么导致了这种差异。