WPF 如何绑定自定义控件的依赖属性
时间: 2024-03-22 14:42:53 浏览: 48
要绑定自定义控件的依赖属性,需要在自定义控件的类中定义依赖属性,并在 XAML 中使用 Binding 绑定该属性。
首先,在自定义控件的类中定义依赖属性,可以使用 DependencyProperty.RegisterAttached 或 DependencyProperty.Register 方法,例如:
```csharp
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.RegisterAttached(
"MyProperty", typeof(string), typeof(MyCustomControl), new PropertyMetadata(null));
public static string GetMyProperty(DependencyObject obj)
{
return (string)obj.GetValue(MyPropertyProperty);
}
public static void SetMyProperty(DependencyObject obj, string value)
{
obj.SetValue(MyPropertyProperty, value);
}
```
然后,在 XAML 中使用 Binding 绑定该属性,例如:
```xaml
<local:MyCustomControl local:MyCustomControl.MyProperty="{Binding MyProperty}" />
```
其中,local 是自定义控件所在的命名空间,MyCustomControl 是自定义控件的类名,MyProperty 是自定义控件的依赖属性名,Binding 是绑定关键字,MyProperty 是数据源中的属性名。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)