日期:2014-05-17  浏览次数:20833 次

WPF统一设置Style的问题
我想让一个StackPanel里面的所有控件(不管是什么类型)都有一样的宽度和高度,我写成
<StackPanel.Resources>
<Style TargetType="{x:Type FrameworkElement}">
<Setter Property="Width" Value="60" />
<Setter Property="Height" Value="50" />
</Style>
</StackPanel.Resources>

却没有效果。如果指定FrameworkElement为某个具体类,如Rectangle、Ellipse等则可以。但我不知道加进来的具体是什么类型的控件。请问如何解决?

------解决方案--------------------
刚才google搜索了下Style,你是通过x:Key来引用的吗?用x:Key的话,那个TargetType就可以使用FrameworkElement了,但是从你给的代码中没有看到x:Key
------解决方案--------------------
你要每个控件都要赋值样式才行,例如:

    <Grid>
        <Grid.Resources>
            <Style x:Key="test1" TargetType="{x:Type FrameworkElement}">
                <Setter Property="Height" Value="30"/>
                <Setter Property="Width" Value=" 100"/>
             </Style>
        </Grid.Resources>
        <TextBox HorizontalAlignment="Left" Margin="92,174,0,0" Name="textBox1" VerticalAlignment="Top"
                 Style="{StaticResource ResourceKey=test1}"  />
        <Button Content="Button"  HorizontalAlignment="Left" Margin="292,172,0,0" Name="button1" VerticalAlignment="Top"
                Style="{StaticResource ResourceKey=test1}" />
    </Grid>

------解决方案--------------------
不指定具体类型的话为每个控件设置Style="{。。。。。。}"
------解决方案--------------------
我试了一下。这样做就可以了
<Grid>
        <StackPanel>
            <StackPanel.Resources>
                <Style x:Key="SDFSDSF" TargetType ="{x:Type  FrameworkElement}">
                    <Setter Property ="Height" Value="200"/>
                    <Setter Property ="Width" Value="20"/>
                </Style>
            </StackPanel.Resources>
            <Button Style="{StaticResource SDFSDSF}">
                SDFSDF
            </Button>
        </StackPanel>