WPF自定义控件使用依赖属性

WPF控件使用依赖属性

1、首先创建一个用户自定义控件,然后随便放一个Button按钮

<Grid> <Button Content="{Binding ButtonText,RelativeSource={RelativeSource AncestorType={x:Type local:UserButtonControl}}}" Width="130" Height="50"></Button> </Grid>
2、后台定义一个依赖属性
public static readonly DependencyProperty ButtonTextProperty = DependencyProperty.Register("ButtonText", typeof(string), typeof(UserButtonControl), new PropertyMetadata("Default Button Text")); public string ButtonText { get { return (string)GetValue(ButtonTextProperty); } set { SetValue(ButtonTextProperty, value); } }
其中四个参数分别是 属性名 属性类型 拥有该属性的类 属性默认值

3、使用这个自定义控件,并给自定义控件的依赖属性赋值
<Grid> <uc:UserButtonControl ButtonText="自定义的值13"></uc:UserButtonControl> </Grid>
然后就可以看到设置的值了

posted @ 2025-02-20 16:02  晨冬之雪  阅读(77)  评论(0)    收藏  举报
百度