C# WPF-将同一样式设置为多个控件
是否可以将同一样式设置为多个控件? 我被试了以下方法。但第一种按钮样式应用不正确,第二种样式应用得很好 设计:C# WPF-将同一样式设置为多个控件,c#,wpf,resourcedictionary,C#,Wpf,Resourcedictionary,是否可以将同一样式设置为多个控件? 我被试了以下方法。但第一种按钮样式应用不正确,第二种样式应用得很好 设计: <StackPanel Orientation="Horizontal"> <TextBlock Foreground="White" Margin="0,0,5,0">1st Button</TextBlock> <Button Style="{StaticResource ViewButton}" /> <
<StackPanel Orientation="Horizontal">
<TextBlock Foreground="White" Margin="0,0,5,0">1st Button</TextBlock>
<Button Style="{StaticResource ViewButton}" />
<TextBlock Foreground="White" Margin="25,0,5,0">2nd Button</TextBlock>
<Button Style="{StaticResource ViewButton}" />
</StackPanel>
<Style x:Key="ViewButton" TargetType="Button" BasedOn="{StaticResource ButtonStyle}">
<Setter Property="Content">
<Setter.Value>
<StackPanel Orientation="Horizontal">
<Image Source="/Images/View.png" Stretch="None" Width="24" Height="24" />
<TextBlock Margin="5,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" FontWeight="Bold">View</TextBlock>
</StackPanel>
</Setter.Value>
</Setter>
<Setter Property="Padding" Value="2,0,10,0"/>
</Style>
第一个按钮
第二个按钮
资源:
<StackPanel Orientation="Horizontal">
<TextBlock Foreground="White" Margin="0,0,5,0">1st Button</TextBlock>
<Button Style="{StaticResource ViewButton}" />
<TextBlock Foreground="White" Margin="25,0,5,0">2nd Button</TextBlock>
<Button Style="{StaticResource ViewButton}" />
</StackPanel>
<Style x:Key="ViewButton" TargetType="Button" BasedOn="{StaticResource ButtonStyle}">
<Setter Property="Content">
<Setter.Value>
<StackPanel Orientation="Horizontal">
<Image Source="/Images/View.png" Stretch="None" Width="24" Height="24" />
<TextBlock Margin="5,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" FontWeight="Bold">View</TextBlock>
</StackPanel>
</Setter.Value>
</Setter>
<Setter Property="Padding" Value="2,0,10,0"/>
</Style>
看法
您将两次相同的内容设置到两个不同的控件。问题是Setter.Value中的StackPanel不能有两个父对象,因此将应用最后一次使用。您可以使用ContentTemplate使其工作:
<Style x:Key="ViewButton" TargetType="Button" BasedOn="{StaticResource ButtonStyle}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="/Images/View.png" Stretch="None" Width="24" Height="24" />
<TextBlock Margin="5,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" FontWeight="Bold">View</TextBlock>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="Padding" Value="2,0,10,0"/>
</Style>
看法
....
....
....
您必须在as按钮中提到TargetType。您需要像我写的那样,在样式名称后面写style属性
希望这对你有用
谢谢您不应该使用模板而不是样式中的内容吗?@JanneMatikainen是的,我以前使用过模板,但我必须使用ContentTemplate才能使其正常工作。最后,Nkonishvt的解决方案帮助了我。。。。谢谢在我试着代替之前。谢谢你给我指路:)