2014-02-12 34 views
2

可以将值或参数传递给WPF用户控件吗?我正在使用MVVM模式。参数可以传递给WPF用户控件吗?

<local:SampleUserControlView Forecolor="{Binding ForeColor}"/> 

其中

前景色为类型颜色或刷在视图模型的 窗口托管SampleUserControl查看的属性。

顺便说一句,应该属性的颜色或刷子类型?

回答

4

是的,你可以通过使用dependency properties。您可以在您的usercontrol中创建您想要传递的类型的依赖项属性。下面是一个小例子,它会告诉你它是如何工作的。

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); 
    } 
} 

而且MyCustom您可以从母VM设置,像

<local:SampleUserControlView MyCustom="{Binding MyCustomValue}"/> 
+0

它没有工作。我可以看到xaml中的值,但依赖项属性没有得到该值。它仍然是空的。 – user2330678

+0

我建议你使用示例代码。我使用相同的方法在Usercontrols之间传递数据。你可以根据你的需要加强这一点。 –

相关问题