读书人

WPF统一设置Style的有关问题

发布时间: 2013-03-10 09:38:39 作者: rapoo

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>


</Grid>


你之所以不好使,应该是style对象没有明确吧,强制指定一下就好了。WPF统一设置Style的有关问题
[解决办法]
引用:
我试了一下。这样做就可以了
C# code?12345678910111213<Grid> <StackPanel> <StackPanel.Resources> <Style x:Key="SDFSDSF" TargetType ="{x:Type FrameworkElement}"> ……

LZ的对象都是动态添加的,他不加x:Key肯定是希望所有FrameworkElement全局应用这个Style,这样后台只要Add进去就自动应用了。不过这样的写法用FrameworkElement这种Type好像是不行的,必须明确指明TargetType.
[解决办法]
引用:
引用:我试了一下。这样做就可以了
C# code?12345678910111213<Grid> <StackPanel> <StackPanel.Resources> <Style x:Key="SDFSDSF" TargetType ="{x:Type F……

动态添加也可以啊,

Style FrameworkElementStyleTest = this.Resources["FrameworkElementStyle"] as Style;
Button a = new Button();
a.Style = FrameworkElementStyleTest;

FrameworkElementStyle是你style的key,这样就ok。
[解决办法]
引用:
引用:引用:我试了一下。这样做就可以了
C# code?12345678910111213<Grid> <StackPanel> <StackPanel.Resources> <Style x:Key="SDFSDSF" Ta……

你的空间是动态添加的,style的对象new一个就行,所有空间遍历一边挨个加style就ok。
[解决办法]
引用:
引用:引用:引用:我试了一下。这样做就可以了
C# code?12345678910111213<Grid> <StackPanel> <StackPanel.Resources> ……

他就是想省这一步嘛。下面不是说了么。。。。

读书人网 >C#

热点推荐