WPF 控件绑定自定义类变量
程序员文章站
2022-03-04 11:28:26
...
WPF控件绑定数据,DataContext属性指定的是窗口本身。如果想要绑定其他自定义类或者变量则需要自己修改DataContext指向的内容。刚开始学习WPF具体原理还需要慢慢弄清楚。
可以参考网友方法
下面的方法只是做了一下优化
方法一
新建类,必须继承INotifyPropertyChanged
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BurnTool
{
public class SeriesNumInfo: INotifyPropertyChanged
{
public int Total { get; set; }
private int mComplete;
public int Complete
{
get { return mComplete; }
set
{
mComplete = value;
CurrentNo = List[mComplete];
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Complete)));
}
}
private string mCurrentNo;
public string CurrentNo
{
get { return mCurrentNo; }
set
{
mCurrentNo = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurrentNo)));
}
}
public SeriesNumInfo()
{
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
DataContext绑定数据
xaml中需要实现的内容,在XAML中设置DataContext,注意要设置:1)引用namespace;2)设置Resources;3)设置DataContext。如下代码所示:
<Window x:Class="DataContext.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:DataContext"
Title="MainWindow" Height="350" Width="525">
<!--DataContext代码中关联则此处不需要-->
<Window.Resources>
<local:SeriesNumInfo x:Key="sni" CurrentNo=""/>
</Window.Resources>
<Grid>
<StackPanel Margin="15">
<!--DataContext代码中关联则此处不需要-->
<WrapPanel Margin="0,20,0,0" Name="WrapPanel" DataContext="{StaticResource sni}">
<TextBox x:Name="tbCurrentSN" Text="{Binding Path=CurrentNo}" Width="50" Margin="5,0"/>
</WrapPanel>
</StackPanel>
</Grid>
</Window>
或者
<Window x:Class="DataContext.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:DataContext"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel Margin="15">
<WrapPanel Margin="0,20,0,0" Name="WrapPanel">
<!--DataContext代码中关联则此处不需要-->
<WrapPanel.DataContext>
<local:SeriesNumInfo CurrentNo=""/>
</WrapPanel.DataContext>
<TextBox x:Name="tbCurrentSN" Text="{Binding Path=CurrentNo}" Width="50" Margin="5,0"/>
</WrapPanel>
</StackPanel>
</Grid>
</Window>
在MainWindow.xaml.cs文件中
private SeriesNumInfo mSeriesNumInfo = null;
public string SNCompletely
{
get
{
if (mSeriesNumInfo == null)
{
mSeriesNumInfo = (SeriesNumInfo)this.FindResource("sni"); // 关联资源,这样后续mSeriesNumInfo 中CurrentNo才能通知到界面
}
}
}
如果在xaml中做DataContext指定,则可以在MainWindow.xaml.cs 文件中实现
private SeriesNumInfo mSeriesNumInfo = null;
public string SNCompletely
{
get
{
if (mSeriesNumInfo == null)
{
mSeriesNumInfo = new SeriesNumInfo();
tbCurrentSN.DataContext = mSeriesNumInfo;// 控件数据关联,这样后续mSeriesNumInfo 中CurrentNo才能通知到界面
}
}
}