几天前我在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的逻辑树中.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。