问题
Can values or parameters be passed to a WPF user control? I am using MVVM pattern.
<local:SampleUserControlView Forecolor="{Binding ForeColor}"/>
where
ForeColor is a property of Type Color or Brush in Viewmodel of the window hosting SampleUserControl View.
By the way, should the property be of type Color or Brush?
回答1:
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.
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 MyCustom
you can set from your parent VM, like
<local:SampleUserControlView MyCustom="{Binding MyCustomValue}"/>
来源:https://stackoverflow.com/questions/21716701/can-parameters-be-passed-to-a-wpf-user-control