WPF用户控件和依赖属性

依赖属性

**定义:**自己没有值,由别人给他赋值

应用场景

  • 要求属性支持绑定(只有依赖属性可以绑定)
  • 自定义控件/扩展控件属性
  • 验证/强制回调
  • 继承
  • 附加属性(一种特殊的依赖属性)

创建依赖属性

快捷键propdp+tab(两次)

可以看到下面代码,创建依赖属性分为三步:定义,注册和包装

cs 复制代码
//包装
public int MyProperty
{
    get { return (int)GetValue(MyPropertyProperty); }
    set { SetValue(MyPropertyProperty, value); }
}

// Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
//定义和注册
public static readonly DependencyProperty MyPropertyProperty =
    DependencyProperty.Register("MyProperty", typeof(int), typeof(ownerclass), new PropertyMetadata(0));

上面代码中Register里面参数内容

属性名称就是页面中控件属性名称,要和属性名称相同

所有者类型是这个属性所在的类的类型

属性元数据是初始属性数据

使用依赖属性来绑定用户控件内部控件属性

当我们将label和textbox作为一个用户控件使用时,要想对label的content属性或者textbox的text进行赋值,无法直接进行。

userControl.xaml文件

在这里面做绑定,绑定自己定义在cs文件里面的依赖属性,绑定方式也要注意不能使用普通的绑定方式,​依赖属性 ​ 是控件的"内置属性",需通过 ElementName来进行绑定,绑定源是控件而非默认的 DataContext

XML 复制代码
<UserControl x:Class="WPF_try.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WPF_try"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800"
               x:Name="root">
    <Grid>
        <StackPanel Orientation="Vertical">
            <Label x:Name="label" Content="{Binding LabelText, ElementName=root}"/>
            <TextBox x:Name="textBox" Width="200" Text="{Binding Text, ElementName=root, Mode=TwoWay}"/>
        </StackPanel>
    </Grid>
</UserControl>

userControl.cs文件

依赖属性,作为整个用户控件对外的设置接口

cs 复制代码
 public partial class UserControl1 : UserControl
 {
     public UserControl1()
     {
         InitializeComponent();
    
     }
     // 标签文本属性
     public static readonly DependencyProperty LabelTextProperty =
         DependencyProperty.Register(
             "LabelText",
             typeof(string),
             typeof(UserControl1),
             new PropertyMetadata("Default Label"));

     // 文本框内容属性
     public static readonly DependencyProperty TextProperty =
         DependencyProperty.Register(
             "Text",
             typeof(string),
             typeof(UserControl1),
             new FrameworkPropertyMetadata(
                 default(string),
                 FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

     public string LabelText
     {
         get { return (string)GetValue(LabelTextProperty); }
         set { SetValue(LabelTextProperty, value); }
     }

     public string Text
     {
         get { return (string)GetValue(TextProperty); }
         set { SetValue(TextProperty, value); }
     }
 }

mainwindow.xaml文件

将依赖属性和cs文件中的属性进行绑定指定他的初始值,或者使用赋值方式给与值

XML 复制代码
<StackPanel>
    <local:UserControl1 LabelText="用户名" Text="{Binding UserName}"/>
    <local:UserControl1 LabelText="密码" Text="{Binding Password}"/>
</StackPanel>

mainwindow.cs文件

cs 复制代码
  public partial class MainWindow : Window
  {
      public MainWindow()
      {
          DataContext = this;
          InitializeComponent();
        
      }
      private string _userName="sdad";
      public string UserName
      {
          get { return _userName; }
          set { _userName = value;  }
      }

      private string _password="123456";
      public string Password
      {
          get { return _password; }
          set { _password = value;  }
      }

  }
相关推荐
国服第二切图仔12 小时前
HarmonyOS APP《画伴梦工厂》开发第60篇-分布式软总线2.0——多设备协同新范式
分布式·wpf·harmonyos
精神底层17 小时前
拒绝 UI 卡死!我用 CSnakes 实时拦截 Python 训练流,在 WPF 中重构了 ScottPlot 5 高性能 AI 看板
python·ui·wpf
爱吃大芒果17 小时前
不用多设备模拟器跑通 ShareKit 碰一碰分享
华为·wpf·harmonyos
贪玩的小松鼠2 天前
WPF基础到企业应用系列7——深入剖析依赖属性(WPF/Silverlight核
wpf
界面开发小八哥2 天前
界面控件DevExpress WPF v26.1新版亮点 - TreeView、Spreadsheet控件功能升级
.net·wpf·界面控件·devexpress·ui开发
斯文的八宝粥3 天前
WPF企业内训全程实录(下)
大数据·hadoop·wpf
精明的身影5 天前
深入WPF -- Dispatcher(补)
wpf
云中飞鸿6 天前
该如何进行WPF界面设计
wpf
云中飞鸿7 天前
WPF分哪几块
wpf
newbe365247 天前
我们如何使用 impeccable 优化前端界面设计与实现稳定性
前端·人工智能·分布式·github·aigc·wpf