[WPF]数据绑定Demo
目录
1、View模型代码
3、数据模型
4、样例演示
5、一些知识点
这里简单实现一个listbox绑定的功能,符合MVVM模型。
View模型代码(View视图以及窗体类的后台代码)
<Grid>
<ListBox Name="ListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Name, Mode=TwoWay}" />
<TextBox Text="{Binding Path=Password}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ViewModel model=new ViewModel(this);
this.ListBox.ItemsSource = model.users;
Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
model.users[0].Name = i.ToString();
Console.WriteLine(i);
Thread.Sleep(1000);
}
});
}
}
ViewModel模型代码
/// <summary>
/// 视图模型
/// </summary>
public class ViewModel
{
public List<User> users { get; set; }
public ViewModel(MainWindow window)
{
users = new List<User>();
for (int i = 0; i < 5; i++)
{
var user = new User()
{
Name = "testname",
Password = "123456"
};
users.Add(user);
}
}
}
数据模型
/// <summary>
/// 数据模型
/// </summary>
public class User:INotifyPropertyChanged
{
private string _name;
public string Name
{
get => _name;
set
{
_name = value;
//这里通知说明数据发生改变了,调用OnPropertyChanged方法
OnPropertyChanged(nameof(Name));
}
}
private string _password;
public string Password
{
get => _password;
set
{
_password = value;
OnPropertyChanged(nameof(Password));
}
}
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// 这里事件派发
/// </summary>
/// <param name="propertyName"></param>
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
样例演示
一些知识点
Text="{Binding Path=Name, Mode=TwoWay}"
可以直接写成:
Text="{Binding Name}"
因为默认就是双向绑定,也可以不加Path,效果一样。
关于数据绑定这一块的详细说明和底层实现可以看这几个博客,我这里就不照抄了:
https://github.com/li-zheng-hao