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

对于集合属性

集合属性

相关推荐
SEO-狼术2 小时前
Telerik UI for WPF and WinForms 2025 Q4 Crack
ui·wpf
武藤一雄3 小时前
[WPF] 万字拆解依赖属性与附加属性
前端·microsoft·c#·.net·wpf
Macbethad4 小时前
工业设备配方管理程序技术方案
wpf
我好喜欢你~4 小时前
.net---图表库(LiveCharts.Wpf)
c#·wpf
分布式存储与RustFS4 小时前
RustFS:基于Rust的高性能分布式对象存储,重新定义数据存储新标准!
人工智能·wpf·对象存储·minio·高可用·企业存储·rustfs
500844 小时前
鸿蒙 Flutter 分布式数据同步:DistributedData 实时协同实战
分布式·flutter·华为·electron·开源·wpf·音视频
后端小张4 小时前
【鸿蒙2025领航者闯关】从技术突破到生态共建,开发者的成长与远航
华为·wpf·生态·harmonyos·鸿蒙·鸿蒙系统·鸿蒙2025领航者试炼
500845 小时前
鸿蒙 Flutter 超级终端适配:多设备流转与状态无缝迁移
java·人工智能·flutter·华为·性能优化·wpf
吃好喝好玩好睡好5 小时前
Redux/MobX 在 OpenHarmony 分布式 Electron+Flutter 应用中的状态管理实战
eclipse·wpf·visual studio
WineMonk19 小时前
WPF 力导引算法实现图布局
算法·wpf