如何在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}"/>
答案 0 :(得分:2)
您将其引用为“ForeColor”,而不是“ForeColorProperty”。
<local:SomeView ForeColor="{Binding Foreground}"/>
要使上述绑定起作用,控件的当前数据上下文中必须有一个“Color”类型的公共属性“Foreground”。
修改强>
如果要将值传递给视图模型,则需要双向绑定:
<local:SomeView ForeColor="{Binding Foreground,Mode=TwoWay}"/>