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

对于集合属性

集合属性

相关推荐
玉面小君2 天前
从 WPF 到 Avalonia 的迁移系列实战篇6:Trigger、MultiTrigger、DataTrigger 的迁移
wpf·avalonia
招风的黑耳3 天前
Java生态圈核心组件深度解析:Spring技术栈与分布式系统实战
java·spring·wpf
lfw20193 天前
WPF 数据绑定模式详解(TwoWay、OneWay、OneTime、OneWayToSource、Default)
wpf
Magnum Lehar3 天前
3d wpf游戏引擎的导入文件功能c++的.h实现
3d·游戏引擎·wpf
FuckPatience4 天前
WPF Telerik.Windows.Controls.Data.PropertyGrid 自定义属性编辑器
wpf
almighty274 天前
C#WPF控制USB摄像头参数:曝光、白平衡等高级设置完全指南
开发语言·c#·wpf·usb相机·参数设置
军训猫猫头4 天前
12.NModbus4在C#上的部署与使用 C#例子 WPF例子
开发语言·c#·wpf
我要打打代码4 天前
在WPF项目中使用阿里图标库iconfont
wpf
拾忆,想起5 天前
Redisson 分布式锁的实现原理
java·开发语言·分布式·后端·性能优化·wpf
weixin_464078075 天前
wpf依赖注入驱动的 MVVM实现(含免费源代码demo)
wpf