可以将参数传递给 WPF 用户控件吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21716701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can parameters be passed to a WPF user control?
提问by user2330678
Can values or parameters be passed to a WPF user control? I am using MVVM pattern.
可以将值或参数传递给 WPF 用户控件吗?我正在使用 MVVM 模式。
<local:SampleUserControlView Forecolor="{Binding ForeColor}"/>
where
在哪里
ForeColor is a property of Type Color or Brush in Viewmodel of the window hosting SampleUserControl View.
ForeColor 是托管 SampleUserControl 视图的窗口的 Viewmodel 中的 Type Color 或 Brush 属性。
By the way, should the property be of type Color or Brush?
顺便说一下,属性应该是颜色类型还是画笔类型?
回答by Mukesh Rawat
yes you can pass by using dependency properties. You can create dependency property in your usercontrol of type what you want to pass. Below is a small example which will show you how it works.
是的,您可以通过使用dependency properties. 您可以在您要传递的类型的用户控件中创建依赖项属性。下面是一个小例子,它将向您展示它是如何工作的。
public static readonly DependencyProperty MyCustomProperty =
DependencyProperty.Register("MyCustom", typeof(string), typeof(SampleUserControl));
public string MyCustom
{
get
{
return this.GetValue(MyCustomProperty) as string;
}
set
{
this.SetValue(MyCustomProperty, value);
}
}
And MyCustomyou can set from your parent VM, like
而且MyCustom您可以从母VM,设置像
<local:SampleUserControlView MyCustom="{Binding MyCustomValue}"/>

