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

对于集合属性

集合属性

相关推荐
wangnaisheng3 小时前
【WPF】WrapPanel的用法
wpf
源之缘-OFD先行者15 小时前
10 万雷达点迹零卡顿回放:WPF + Vortice.Direct2D 多线程渲染实战
wpf
猫林老师1 天前
Flutter for HarmonyOS开发指南(九):测试、调试与质量保障体系
flutter·wpf·harmonyos
LateFrames1 天前
做【秒开】的程序:WPF / WinForm / WinUI3 / Electron
electron·c#·wpf·winform·winui3·claude code
beyond谚语1 天前
第四章 依赖项属性
wpf
国服第二切图仔2 天前
鸿蒙应用开发之实现键值型数据库跨设备数据同步
数据库·wpf·harmonyos
玖笙&2 天前
✨WPF编程进阶【7.1】动画基础
c++·c#·wpf·visual studio
专注VB编程开发20年2 天前
探讨vs2022在net6框架wpf界面下使用winform控件
framework·.net·wpf·winform·cefsharp·miniblink·geckofx45
刘一说2 天前
Spring Boot 中的定时任务:从基础调度到高可用实践
spring boot·后端·wpf
FuckPatience2 天前
WPF 获取鼠标相对于控件的坐标信息,控制控件锚点放缩
wpf