这听起来像是Attached properties的工作。
使用“占位符属性”创建一个实用程序类:
public static class BigButtonUtils
{
public static Uri GetBBImage(DependencyObject obj)
{
return (Uri)obj.GetValue(BBImageProperty);
}
public static void SetBBImage(DependencyObject obj, Uri value)
{
obj.SetValue(BBImageProperty, value);
}
// Using a DependencyProperty as the backing store for BBImage. This enables animation, styling, binding, etc...
public static readonly DependencyProperty BBImageProperty =
DependencyProperty.RegisterAttached("BBImage", typeof(Uri), typeof(BigButtonUtils), new UIPropertyMetadata(null));
public static string GetBBCaption(DependencyObject obj)
{
return (string)obj.GetValue(BBCaptionProperty);
}
public static void SetBBCaption(DependencyObject obj, string value)
{
obj.SetValue(BBCaptionProperty, value);
}
// Using a DependencyProperty as the backing store for BBCaption. This enables animation, styling, binding, etc...
public static readonly DependencyProperty BBCaptionProperty =
DependencyProperty.RegisterAttached("BBCaption", typeof(string), typeof(BigButtonUtils), new UIPropertyMetadata(null));
}
将这些属性应用于 Button..
<Button Style="{StaticResource BigButtonStyle}"
bb:BigButtonUtils.BBImage="http://programming.enthuses.me/1.png"
bb:BigButtonUtils.BBCaption="My caption" />
..并在您的样式中使用属性值:
<Style x:Key="BigButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Foreground" Value="#58290a" />
<Setter Property="FontFamily" Value="Lucida Console" />
<Setter Property="FontSize" Value="24" />
<Setter Property="Content">
<Setter.Value>
<StackPanel DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Button}}">
<Image Source="{Binding Path=(bb:BigButtonUtils.BBImage)}" Stretch="None" />
<TextBlock Text="{Binding Path=(bb:BigButtonUtils.BBCaption)}" />
</StackPanel>
</Setter.Value>
</Setter>
</Style>
注意:不要在 Button 上设置任何其他内容,例如<Button Content="..." />
或<Button ...>SomeContent</Button>
,因为这会覆盖样式中的“占位符内容”。