WPF绑定到自定义控件的属性
我创建了一个自定义控件,表示从控件派生的类,该控件关联通过Themes/Generic.xaml定义的默认无外观主题。到目前为止还不错 现在,我想像其他任何主要WPF控件(textbox、listbox、label、textblock等)一样使用该控件,并绑定到定义的属性 自定义控件定义了一个名为Value的属性,我喜欢将其设置为绑定。但是,在DataContext中,不会向绑定属性写入任何内容 好吧,这是我到目前为止得到的: 在自定义控件类中,有以下内容:WPF绑定到自定义控件的属性,wpf,binding,custom-controls,dependency-properties,Wpf,Binding,Custom Controls,Dependency Properties,我创建了一个自定义控件,表示从控件派生的类,该控件关联通过Themes/Generic.xaml定义的默认无外观主题。到目前为止还不错 现在,我想像其他任何主要WPF控件(textbox、listbox、label、textblock等)一样使用该控件,并绑定到定义的属性 自定义控件定义了一个名为Value的属性,我喜欢将其设置为绑定。但是,在DataContext中,不会向绑定属性写入任何内容 好吧,这是我到目前为止得到的: 在自定义控件类中,有以下内容: public static read
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
"Value", typeof(string), typeof(MyClass),
new FrameworkPropertyMetadata("", new PropertyChangedCallback(onValuePropertyChangedCallback)));
private static void onValuePropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
MyClass myClass = (MyClass)sender;
myClass.Value = (string)args.NewValue;
}
public string Value
{
get { return (string) GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
当我使用控件时,是这样的
<local:MyClass MyValue="{Binding CurrentValue}" ... />
DataContext的CurrentValue属性不会受到影响,也不会更改其值
我做错了什么 要更新源属性,与的绑定应该是双向的:
<local:MyClass Value="{Binding CurrentValue, Mode=TwoWay}" ... />
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
nameof(Value), typeof(string), typeof(MyClass),
new FrameworkPropertyMetadata(
"", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public string Value
{
get { return (string)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
请注意,您的
onValuePropertyChangedCallback
是完全冗余的。当属性值刚刚更改时,您无需再次设置属性。非常感谢!我假设BindingMode在默认情况下是双向的。现在,我已经设置了绑定模式,一切正常。再次感谢!