参数可以传递给WPF用户控件吗?

use*_*678 2 .net c# wpf prism mvvm

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

<local:SampleUserControlView Forecolor="{Binding ForeColor}"/> 
Run Code Online (Sandbox Code Playgroud)

哪里

ForeColor是托管SampleUserControl View的窗口的Viewmodel中的Type Color或Brush的属性.

顺便说一下,属性应该是Color还是Brush?

Muk*_*wat 5

是的,你可以通过使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<local:SampleUserControlView MyCustom="{Binding MyCustomValue}"/> 
Run Code Online (Sandbox Code Playgroud)

  • @user2330678你是对的,这不会起作用 (2认同)