WPF - 自定义控件集填充到矩形

时间:2017-01-04 07:19:00

标签: wpf

我有自定义控件图标,其中包含矩形。我将Fill默认设置为父值。但有时我想将填充设置为任何颜色。我不想为Fill创建DependencyProperty。是替代方案吗? 这是我的代码:

图标控件:

<UserControl>
    <Rectangle Width="12" Height="12" 
               Fill="{Binding Path=Foreground, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Control}, AncestorLevel=3}}">
        <Rectangle.OpacityMask>
            <VisualBrush Stretch="Fill" Visual="{Binding Path=Picture, RelativeSource={RelativeSource AncestorType={x:Type local:Icon}}}" />
        </Rectangle.OpacityMask>
    </Rectangle>
</UserControl>



public partial class Icon
    {
        public static readonly DependencyProperty PictureProperty
            = DependencyProperty.Register("Picture", typeof(Canvas), typeof(Icon));

        public Canvas Picture
        {
            get { return (Canvas)GetValue(PictureProperty); }
            set { SetValue(PictureProperty, value); }
        }

        public Icon()
        {
            InitializeComponent();
        }
    }

用法 这有效:

<controls:Icon Picture="{StaticResource appbar_calendar}"/>

这也是:

<controls:Icon Picture="{StaticResource appbar_calendar}" Fill="Yellow"/>

我想要两种选择。 感谢

1 个答案:

答案 0 :(得分:1)

由于UserControl没有Fill属性,您可以使用其Background属性来填充Rectangle:

<强> Icon.xaml:

<UserControl x:Class="WpfApplication1.Icon"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApplication1"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300"
             x:Name="uc">
    <UserControl.Template>
        <ControlTemplate TargetType="UserControl">
            <Rectangle Width="12" Height="12" 
                   Fill="{TemplateBinding Background}">
                <Rectangle.OpacityMask>
                    <VisualBrush Stretch="Fill" Visual="{Binding Path=Picture, RelativeSource={RelativeSource AncestorType={x:Type local:Icon}}}" />
                </Rectangle.OpacityMask>
            </Rectangle>
        </ControlTemplate>
    </UserControl.Template>
</UserControl>

<强> Icon.xaml.cs:

public partial class Icon : UserControl
{
    public static readonly DependencyProperty PictureProperty
         = DependencyProperty.Register("Picture", typeof(Canvas), typeof(Icon));

    public Canvas Picture
    {
        get { return (Canvas)GetValue(PictureProperty); }
        set { SetValue(PictureProperty, value); }
    }

    public Icon()
    {
        InitializeComponent();
    }
}

<强> Window.xaml:

<controls:Icon Picture="{StaticResource appbar_calendar}" Background="Yellow"/>

这是替代方案。如果你真的想要一个Fill属性,你当然必须定义另一个名为&#34; Fill&#34;在您的自定义Icon类中。

相关问题