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}"

对于集合属性

集合属性

相关推荐
棉晗榜1 小时前
WPF印章水印, Border怎么悬浮在其他控件上面,类似盖章一样
wpf
张人玉2 小时前
LiveCharts WPF MVVM 图表开发笔记
大数据·分布式·wpf·livecharts
武藤一雄2 小时前
一款基于WPF开发的BEJSON转换工具
windows·c#·json·wpf
Poetinthedusk6 小时前
设计模式-模板方法模式
windows·设计模式·c#·wpf·模板方法模式
武藤一雄1 天前
[奇淫巧技] WPF篇 (长期更新)
windows·microsoft·c#·.net·wpf
Psycho_MrZhang1 天前
Airflow简介和架构
架构·wpf
没有bug.的程序员1 天前
微服务中的数据一致性困局
java·jvm·微服务·架构·wpf·电商
Aevget1 天前
DevExpress WPF中文教程:Data Grid - 如何绑定到有限制的自定义服务(二)?
wpf·devexpress·.net 10·data grid
没有bug.的程序员3 天前
SOA、微服务、分布式系统的区别与联系
java·jvm·微服务·架构·wpf·日志·gc
Macbethad3 天前
基于WPF的半导体设备配方管理程序技术方案
wpf