重用控制模板,定义了多个控件

时间:2018-01-22 12:03:23

标签: wpf wpf-controls

我很少被困在场景中: 我在resources.xaml中为按钮定义了一种样式。此样式包含控件模板,其中我有堆栈面板,按钮,网格等。按钮具有图像。 我想将此样式与其他按钮一起使用。但唯一的区别是图片网址会有所不同。

任何人都可以给我这方面的提示。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

这可以通过声明图像源的附加属性来完成:

public static class ButtonExtensions
{
    #region ImageSource Attached Property

    public static readonly DependencyProperty ImageSourceProperty =
        DependencyProperty.RegisterAttached(
            "ImageSource",
            typeof(ImageSource),
            typeof(ButtonExtensions),
            new PropertyMetadata(default(ImageSource)));

    public static void SetImageSource(ButtonBase element, ImageSource value)
    {
        element.SetValue(ImageSourceProperty, value);
    }

    [TypeConverter(typeof(ImageSourceConverter))]
    public static ImageSource GetImageSource(DependencyObject element)
    {
        return (ImageSource)element.GetValue(ImageSourceProperty);
    }

    #endregion
}

然后,在您的模板中,您应该包含一个Image,其ImageSource绑定到此属性。

<Image Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(l:ButtonExtensions.ImageSource)}" />

要使用它,只需在应包含图像的每个Button上设置附加属性:

<Button Content="Test Button"
        l:ButtonExtensions.ImageSource="Path/To/Image.png" />

确保将CLR名称空间导入Xaml:

xmlns:l="clr-namespace:Your.Namespace"

理想情况下,您应该设计模板,以便在未通过新属性提供图像源时折叠图像。这样,所有按钮看起来都是正确的,无论它们是否包含图像。

相关问题