如何在UserControl中创建/ WPF依赖属性



如何在UserControl中创建/WPF依赖关系属性?是否可以通过ViewModel创建它?

public partial class SomeView : UserControl
{   
    SomeViewModel vm = new SomeViewModel(ForeColor);
    public SomeView()
    {
        InitializeComponent();
        this.DataContext = vm;
    }
    public Color ForeColor
    {
        get { return (Color)this.GetValue(ForeColorProperty); }
        set { this.SetValue(ForeColorProperty, value); }
    }
    public static readonly DependencyProperty ForeColorProperty = DependencyProperty.Register("ForeColor", typeof(Color), typeof(SomeView));
}

然后像以下那样调用控件不起作用。

 <local:SomeView ForeColorProperty="{Binding Foreground}"/>

您将其引用为"预彩",而不是" forecolorproperty"。

<local:SomeView ForeColor="{Binding Foreground}"/>

对于上述与工作的绑定,必须在控件的当前数据上下文中具有"颜色"类型的"前景"。

编辑

如果要将值传递给视图模型,则需要双向绑定:

<local:SomeView ForeColor="{Binding Foreground,Mode=TwoWay}"/>

最新更新