WPF 控件数据源绑定

WPF 控件数据源绑定

前提:我的数据源都放在 DataProcessView 类中,然后在 MainWindow 中声明该类的对象 DataProcess,如果是指定了 DataContext ,就将该对象赋值给 DataContext (如下),否则不赋值

csharp 复制代码
public partial class MainWindow : Window
{
    public DataProcessView DataProcess { get; set; }//需要指定为 public 权限
    public MainWindow()
    {
        InitializeComponent();
        DataProcess = new DataProcessView();
        this.DataContext = DataProcess;
    }
}

对于普通属性、

csharp 复制代码
public class DataProcessView : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;
	private string _currenttime;
	public string CurrentTime
	 {
	     get { return _currenttime; }
	     set
	     {
	         if (_currenttime != value)
	         {
	             _currenttime = value;
	             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CurrentTime"));
	         }
	     }
	 }
}

指定 DataContext 的前提下,为一个 Label 控件 Context 在 xaml 中赋值,如下:

csharp 复制代码
Content="{Binding CurrentTime}"

未指定 DataContext 的前提下,未指定就需要将数据源的路径给写清楚

csharp 复制代码
Content="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=DataProcess.CurrentTime}"

对于类属性

csharp 复制代码
public class DataProcessView : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;
	private ButtonModel _btn1text;
    public ButtonModel Btn1Text
    {
        get { return _btn1text; }
        set
        {
            if (_btn1text != value)
            {
                _btn1text = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Btn1Text"));
            }
        }
    }
}

指定 DataContext 的前提下,为一个 Button 控件 Context 在 xaml 中赋值,如下:

csharp 复制代码
Content="{Binding Path=BtnGuanBiYYText.Text}"

未指定 DataContext 的前提下,未指定就需要将数据源的路径给写清楚

csharp 复制代码
Content="{Binding RelativeSource ={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=DataProcess.Btn1Text.Text}"

对于集合属性

集合属性

相关推荐
姬激薄4 小时前
配置Hadoop集群-集群配置
wpf
python算法(魔法师版)4 小时前
.NET 在鸿蒙系统上的适配现状
华为od·华为·华为云·.net·wpf·harmonyos
大道随心15 小时前
【wpf】11 在WPF中实现父窗口蒙版效果:原理详解与进阶优化
wpf
zizisuo1 天前
9.1.领域驱动设计
wpf
大道随心1 天前
【wpf】10 C#树形控件高效实现:递归构建与路径查找优化详解
开发语言·c#·wpf
离歌漠1 天前
WPF内嵌其他进程的窗口
c#·wpf
沉到海底去吧Go2 天前
【身份证识别表格】批量识别身份证扫描件或照片保存为Excel表格,怎么大批量将身份证图片转为excel表格?基于WPF和腾讯OCR的识别方案
ocr·wpf·excel·身份证识别表格·批量扫描件身份证转表格·图片识别表格·图片识别excel表格
csdn_aspnet2 天前
WPF 性能 UI 虚拟化 软件开发人员的思考
ui·wpf
冰茶_2 天前
WPF之绑定模式深入
学习·microsoft·微软·c#·wpf·绑定模式
Vae_Mars2 天前
WPF中如何自定义控件
wpf