我一直在我的Xaml文件中提取一些属性为元素的样式。 我有很多重复的块,比如:
<controls:RoundableToggleRadioButton Style="{StaticResource RoundableToggleRadioButtonStyle}">
<StackPanel>
<Image Width="32"
Margin="2"
Source="Images/inbox_upload.png" />
<TextBlock Margin="2"
Foreground="White"
Text="Extract"
TextAlignment="Center" />
</StackPanel>
所以我想为每个按钮提取相同的属性以进行样式设置,并且能够更改图像和文本。像这样:
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel>
<Image Width="32"
Margin="2" />
<TextBlock Margin="2"
Foreground="White"
TextAlignment="Center" />
</StackPanel>
</DataTemplate>
</Setter.Value>
<controls:RoundableToggleRadioButton Style="{StaticResource RoundableToggleRadioButtonStyle}">
<StackPanel>
<Image Source="Images/inbox_upload.png" />
<TextBlock Text="Extract"/>
</StackPanel>
所有可能吗?或者有一些解决方法? 感谢您的帮助)))
答案 0 :(得分:2)
创建继承Button
的新类public class ImageTextButton : Button
{
public static readonly DependencyProperty IconProperty =
DependencyProperty.Register("Icon", typeof (ImageSource), typeof (ImageTextButton), null);
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof (string), typeof (ImageTextButton), null);
public ImageTextButton()
{
this.DefaultStyleKey = typeof(ImageTextButton);
}
public ImageSource Icon
{
get { return (ImageSource) GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
public string Text
{
get { return (string) GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
}
<强> XAML 强>
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfApplication3="clr-namespace:WpfApplication3"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="{x:Type wpfApplication3:ImageTextButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type wpfApplication3:ImageTextButton}">
<StackPanel Height="Auto" Orientation="Horizontal">
<Image Source="{TemplateBinding Icon}" Stretch="Fill"/>
<TextBlock Text="{TemplateBinding Text}"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<wpfApplication3:ImageTextButton Text="Submit" Icon="Hydrangeas.jpg"></wpfApplication3:ImageTextButton>
</Grid>
您也可以使用Button的Content属性,而不是创建新的Text属性。
答案 1 :(得分:1)
如果你有这么多xaml文件并且必须在任何地方应用相同的样式,你可以使用应用程序资源来做到这一点。
以下是一些代码(在app.xaml
)
<Application.Resources>
<Style TargetType="Button" x:Key="ButtonStyling" >
<Setter Property="Margin" Value="1,2,1,2"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
</Style>
</Application.Resources>
然后,对于你的按钮(例如):
<Button Height="50" Width="250" Style="{StaticResource ButtonStyling}" Content="Button 1" />
<Button Height="50" Width="250" Style="{StaticResource ButtonStyling}" Content="Button 2" />
希望这能帮助您找到所需内容。