【问题标题】:Custom UserControl (button) in XAML with parametersXAML 中带有参数的自定义 UserControl(按钮)
【发布时间】:2012-12-27 20:51:40
【问题描述】:

我想制作一个用户控件,我可以将它重用于我的应用程序中的各种按钮。有没有办法通过 XAML 将参数传递给 UserControls?我的应用程序中的大多数按钮将由两个矩形(一个在另一个中)和一些用户指定的颜色组成。它也可能有图像。我希望它表现得像这样:

<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 代码。

谢谢!

【问题讨论】:

    标签: c# wpf xaml windows-8


    【解决方案1】:

    是的,您可以在 xaml 中访问 Control 中的任何属性,但如果您想要 DataBind、Animate 等,您的 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" />
    

    【讨论】:

    • 我这样做了,我可以按照您的建议设置用户控件上的属性。我如何从用户控件中访问它?
    • 经过一番搜索,我发现“{Binding Path=MyVarColor1}”可以工作...感谢您的帮助!
    【解决方案2】:

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

    这里有一个类似的问题:Naming user controls without default constructors in XAML

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      • 2017-10-05
      • 2019-07-11
      • 1970-01-01
      • 2014-02-09
      • 2020-09-26
      相关资源
      最近更新 更多