Jor*_*mar 1 c# wpf xaml windows-8
我想创建一个UserControl,我可以重用我的应用程序中的各种按钮.有没有办法通过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>
Run Code Online (Sandbox Code Playgroud)
然后在按钮内我希望能够在XAML中使用这些值(将IconUrl分配给Icon的源等,等等.
我只是想错误的方式,还是有办法做到这一点?我的目的是为我的所有按钮提供更少的XAML代码.
谢谢!
是的,你可以访问in Controlin xaml中的任何属性,但是如果你想要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));
}
Run Code Online (Sandbox Code Playgroud)
XAML:
<Controls:MyCustomButton MyVarColor1="AliceBlue" MyVarIconUrl="myImageUrl" MyVarIconX="60" />
Run Code Online (Sandbox Code Playgroud)