2010-07-31 38 views
6

我的WPF UserControl包含兩個堆棧面板,每個面板都包含標籤,文本框和單選按鈕。
我想使用盡可能少的代碼將VerticalAlignment屬性設置爲Center以使用我的UserControl中的所有控件。將VerticalAlignment屬性設置爲所有控件

現在我有以下解決方案:

  • 蠻力 - 把VerticalAlignment="Center"在每個控制
  • 定義一個樣式FrameworkElement然後直接將其
  • 定義樣式用戶控制每種類型的控件(這需要3種樣式定義,但自動將樣式應用於控件)

這三種解決方案需要太多的代碼。
有沒有其他的方式來寫這個?
我希望爲FrameworkElement定義樣式會自動將屬性設置爲所有控件,但它不起作用。

這裏是我當前的XAML的片段(我省略第二,非常相似的堆疊面板):

<UserControl.Resources> 
    <Style x:Key="BaseStyle" TargetType="FrameworkElement"> 
     <Setter Property="VerticalAlignment" Value="Center" /> 
    </Style> 
</UserControl.Resources> 
<Grid> 
    <StackPanel Orientation="Horizontal"> 
     <TextBlock Style="{StaticResource BaseStyle}" Text="Value:" /> 
     <RadioButton Style="{StaticResource BaseStyle}">Standard</RadioButton> 
     <RadioButton Style="{StaticResource BaseStyle}">Other</RadioButton> 
     <TextBox Style="{StaticResource BaseStyle}" Width="40"/> 
    </StackPanel> 
</Grid> 

編輯:
重新威爾的評論:我真的很討厭寫控制代碼隱藏格式化代碼的想法。 XAML應該足以實現這個非常簡單的用戶控制。

Re Muad'Dib的評論:在我的用戶控件中使用的控件來自FrameworkElement,所以這不是問題。

+0

將設置此通過在代碼背後是一個可怕的想法,因爲我認爲它會? – 2010-07-31 19:55:21

+0

並非所有的控件都繼承自FrameworkElement – 2010-07-31 20:28:15

回答

9

我之前也遇到過同樣的難題。不知道這是否是「最好」的方式,但通過定義基本風格併爲頁面上繼承自基本風格的每個控件創建單獨樣式很容易:

<Page 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="500" Height="300" Background="OrangeRed"> 

<Page.Resources> 
    <Style TargetType="FrameworkElement" x:Key="BaseStyle"> 
    <Setter Property="VerticalAlignment" Value="Center" /> 
    <Setter Property="Margin" Value="0,0,5,0" /> 
    </Style> 

    <Style TargetType="TextBlock" BasedOn="{StaticResource BaseStyle}" /> 
    <Style TargetType="RadioButton" BasedOn="{StaticResource BaseStyle}" /> 
    <Style TargetType="TextBox" BasedOn="{StaticResource BaseStyle}" /> 
</Page.Resources> 

<Grid> 
    <StackPanel Orientation="Horizontal"> 
     <TextBlock Text="Value:" /> 
     <RadioButton>Standard</RadioButton> 
     <RadioButton>Other</RadioButton> 
     <TextBox Width="75"/> 
    </StackPanel> 
</Grid> 

</Page> 
+0

是的,資源中有三行更多,但控件中的混亂更少。看起來比我現在的代碼好。 – zendar 2010-07-31 22:50:26

相關問題