c# – 重写的TextBlock样式的奇怪行为
|
几天前我在Button中遇到了奇怪的文本行为(我猜其他ContentControls的行为也是如此).让我解释一下情况.我在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;
}
现在我们看到了什么?正如预期的那样,第一个和第三个按钮中的文本边距为0px,但第二个按钮中的文本边距为10px!问题是:为什么第二个按钮具有10px边距以及如何为第二个按钮设置零边距(从App.xaml中删除样式是不可能的)? 谢谢! 解决方法
当我改变
Button2.Content = "Button with string"; 至 Button2.Content = "Button with _string"; 按钮的边距从10变为0. 这是WPF中的一个错误;它已经在Microsoft Connect报道了. 我不是百分百肯定,但我认为你看到的行为是由相同的根本原因引起的. 顺便说一句:正确的行为是按钮2和3有Margin = 10;这是因为资源查找是沿着逻辑树而不是沿着可视树执行的.按钮2和3中的TextBlocks不在StackPanel的逻辑树中. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
