c# - 带参数的 XAML 中的自定义 UserControl(按钮)

标签 c# wpf xaml windows-8

我想制作一个用户控件,我可以将其重复用于应用程序中的各种按钮。有没有办法通过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 代码。

谢谢!

最佳答案

是的,您可以访问 xaml 中 Control 中的任何属性,但如果您想要 DataBind、Animate 等,UserControl 中的属性必须是 依赖属性

示例:

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" />

关于c# - 带参数的 XAML 中的自定义 UserControl(按钮),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14061151/

相关文章:

c# - 新的WPF项目将无法编译-抛出错误 “The name ' InitializeComponent'在当前上下文中不存在”

wpf - 为什么偏爱 RelayCommand 而不是 RoutedCommand?

c# - 如何将 TreeViewItem 放入生成的 TreeViewItem 中?

c# - C# 中的 WPF 类型初始化异常

silverlight - WP7应用程序的反馈表

c# - 为什么要创建一个引用派生类的基类对象

c# - 错误捕获来自(第三方)Web服务的响应信息

c# - 使用参数化构造函数从标记设置 View 的 DataContext

c# - HTML 敏捷包

c# - 暂停一个新的 BackGroundWorker 直到上一个完成