我想让一个StackPanel里面的所有控件(不管是什么类型)都有一样的宽度和高度,我写成
<StackPanel.Resources>
<Style TargetType="{x:Type FrameworkElement}">
<Setter Property="Width" Value="60" />
<Setter Property="Height" Value="50" />
</Style>
</StackPanel.Resources>
却没有效果。如果指定FrameworkElement为某个具体类,如Rectangle、Ellipse等则可以。但我不知道加进来的具体是什么类型的控件。请问如何解决?
<StackPanel.Resources>
<Style TargetType="{x:Type FrameworkElement}">
<Setter Property="Width" Value="60" />
<Setter Property="Height" Value="50" />
</Style>
</StackPanel.Resources>
却没有效果。如果指定FrameworkElement为某个具体类,如Rectangle、Ellipse等则可以。但我不知道加进来的具体是什么类型的控件。请问如何解决?
<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>
不是通过x:Key。控件是后台动态创建和修改的,根据情况可能先创建一些Rectangle,过一会把这些Rectangle清掉换成Ellipse,等等。我的初衷是在前台写好样式之后,后台直接把控件new出来之后丢进来就行了。现在得多一步,通过Key找到Style赋给生成的控件,这确实也是一个方法。
<ItemsControl.ItemTemplate>
<DataTemplate>
<Viewbox Width="60" Height="50" Stretch="Uniform">
<ContentControl Content="{Binding}">
</ContentControl>
</Viewbox>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
试试这个
<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对象没有明确吧,强制指定一下就好了。
....
</WrapPanel>
Style FrameworkElementStyleTest = this.Resources["FrameworkElementStyle"] as Style;
Button a = new Button();
a.Style = FrameworkElementStyleTest;
FrameworkElementStyle是你style的key,这样就ok。
如果一行c#都不想写,也不想没个都不停的添加style,肯定要用ItemsPanel,8楼说的基本没错,但是不应该设置DataTemplate,而是设置ItemContainerStyle的表现形式
<ItemsControl>
<ItemsControl.ItemContainerStyle>
<Style TargetType="{x:Type FrameworkElement}">
<Setter Property="Width" Value="60" />
<Setter Property="Height" Value="50" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<TextBlock Text="1111" Background="Yellow"/>
<Button Content="123"/>
<Rectangle Fill="Black"/>
</ItemsControl>