WPF用户控件是否可以传递参数?

6
可以将值或参数传递给WPF用户控件吗?我正在使用MVVM模式。
<local:SampleUserControlView Forecolor="{Binding ForeColor}"/> 

在承载SampleUserControl视图的窗口的Viewmodel中,ForeColor是Color或Brush类型的属性。

顺便问一下,该属性应该是Color类型还是Brush类型?

1个回答

9

使用依赖属性,您可以传递参数。您可以在用户控件中创建所需类型的依赖属性。以下是一个小例子,它将向您展示它是如何工作的。

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,例如:

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

它没有起作用。我可以在XAML中看到该值,但依赖属性没有获取该值。它仍然为空。 - user2951819
我向您提供了一种使用示例代码的方法。我正在使用相同的方法来在用户控件之间传递数据。您可以根据自己的需要进行增强。 - Mukesh Rawat
1
@user2330678,你是对的,这样做不会起作用。 - abdou_dev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接