带有参数的XAML中自定义USERCONTROL(按钮)



我想制作一个可以重复使用应用程序中各种按钮的USerControl。有没有办法通过XAML将参数传递给USERCONTROL?我的应用程序中的大多数按钮将由两个矩形(另一个内)组成,其中一些用户指定的颜色。它也可能具有图像。我希望它的行为以下:

<Controls:MyCustomButton MyVarColor1="<hard coded color here>" MyVarIconUrl="<null if no icon or otherwise some URI>" MyVarIconX="<x coordinate of icon within button>" etc etc>

然后在按钮内,我希望能够在XAML内使用这些值(将ICONURL分配给图标的源等。

我只是以错误的方式考虑这一点,还是有办法做到这一点?我的目的是为我所有按钮的XAML代码更少。

谢谢!

是的,您可以访问XAML中的Control中的任何属性,但是如果您想数据宾灵语,动画等,则UserControl中的属性必须为DependencyProperties

示例:

public class MyCustomButton : UserControl
{
    public MyCustomButton()
    {
    }
    public Brush MyVarColor1
    {
        get { return (Brush)GetValue(MyVarColor1Property); }
        set { SetValue(MyVarColor1Property, value); }
    }
    // Using a DependencyProperty as the backing store for MyVarColor1.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyVarColor1Property =
        DependencyProperty.Register("MyVarColor1", typeof(Brush), typeof(MyCustomButton), new UIPropertyMetadata(null));

    public double MyVarIconX
    {
        get { return (double)GetValue(MyVarIconXProperty); }
        set { SetValue(MyVarIconXProperty, value); }
    }
    // Using a DependencyProperty as the backing store for MyVarIconX.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyVarIconXProperty =
        DependencyProperty.Register("MyVarIconX", typeof(double), typeof(MyCustomButton), new UIPropertyMetadata(0));

    public Uri MyVarIconUrl
    {
        get { return (Uri)GetValue(MyVarIconUrlProperty); }
        set { SetValue(MyVarIconUrlProperty, value); }
    }
    // Using a DependencyProperty as the backing store for MyVarIconUrl.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyVarIconUrlProperty =
        DependencyProperty.Register("MyVarIconUrl", typeof(Uri), typeof(MyCustomButton), new UIPropertyMetadata(null));
}

xaml:

<Controls:MyCustomButton MyVarColor1="AliceBlue" MyVarIconUrl="myImageUrl" MyVarIconX="60" />

如果您在谈论XAML中传递构造函数参数,则不可能。初始化对象后,您必须通过属性设置它们,否则您需要通过代码进行实例化。

这里有一个类似的问题:命名用户控件在XAML中没有默认构造函数

最新更新