2012-06-09 50 views
4

前幾天我遇到了Button內部文本的奇怪行爲(我想我會得到其他ContentControls的相同行爲)。讓我解釋一下情況。我在App.xaml中的樣式定義的TextBlock:被忽略的TextBlock樣式的奇怪行爲

<Application.Resources> 
    <Style TargetType="{x:Type TextBlock}"> 
     <Setter Property="Margin" Value="10"/> 
    </Style> 
</Application.Resources> 

在MainWindow.xaml我也有同樣的風格定義,應覆蓋在App.xaml中定義的樣式。另外我在窗口中有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中刪除樣式是不可能的)?

謝謝!

+0

[snoop](http://snoopwpf.codeplex.com/)會顯示什麼? –

+0

我試過你的代碼:Snoop說第二個TextBlock有Margin = 10,而其他TextBlocks的Margin = 0。價值來源是所有三種情況下的一種風格。目前,我不知道是什麼導致了差異。 – 2012-06-09 19:49:07

回答

2

當我改變

Button2.Content = "Button with string"; 

Button2.Content = "Button with _string"; 

按鈕的餘量爲10至0

這是WPF的錯誤改變;它已經被報告在Microsoft Connect

我不是100%確定,但我認爲你看到的行爲是由相同的根本原因造成的。順便說一下:正確的行爲是按鈕2和3的邊距= 10;這是因爲資源查找沿着邏輯樹執行,而不是沿着可視化樹執行。按鈕2和3中的TextBlocks不在StackPanel的邏輯樹內。

0

我不能給你一個明確的答案,但我注意到這是設置一個字符串和一個整數,導致不同的風格被應用的區別。

由於設置內容到需要在正確的風格轉換結果的值被應用,我想這一點:

private void WindowLoaded(object sender, RoutedEventArgs e) 
{ 
    Button2.Content = new TextHolder("Button with string"); 
    Button3.Content = 16; 
} 

public class TextHolder 
{ 
    private readonly string _text; 

    public TextHolder(string text) 
    { 
     _text = text; 
    } 

    public override string ToString() 
    { 
     return _text; 
    } 
} 

現在的利潤率是0。我是否有興趣瞭解究竟是怎麼回事。

+0

感謝您解決此問題。這真的很有用。 – core