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