由于要现学现卖,希望尽快掌握用法,但xaml的复杂度超出我的预期,可能会者不难吧。
需要实现一个TreeView与后台数据绑定,总调不成功,又从头学习简单绑定。网上例子很多,但往往举得复杂,消耗无谓的看代码精力。
自己做了一个简单的例子,实现前后端数据绑定、同步刷新。
关键点:
1、后端改变前端时,要实现INotifyPropertyChanged,即通知前端刷新数据。
2、前端改变后端时,绑定要有{..., UpdateSourceTrigger=PropertyChanged},即触发刷新后端。
代码如下
前端xaml:
<Window x:Class="TestDataBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TestDataBinding"
mc:Ignorable="d"
Title="MainWindow" Height="227" Width="517">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" Orientation="Horizontal">
<TextBlock TextWrapping="Wrap" Text="Name "/>
<!--如果只是{Binding Name},前端改变数据后,后端不会刷新-->
<TextBox Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="80"/>
<Button Content="Set Name is Mike" Click="Button_Click"/>
<Button Content="Get Current Name" Click="Button_Click_1" Margin="5,0"/>
</StackPanel>
</Window>
后端C#
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TestDataBinding
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Student student;
public MainWindow()
{
InitializeComponent();
// 创建绑定DataContext,前后端相互绑定后,通过DataContext交换数据.
student = new() {Name = "Tom"};
this.DataContext = student;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// 后台设置Name
student.Name = "Mike";
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
// 测试当前的Name
Debug.WriteLine(student.Name);
}
}
class Student:INotifyPropertyChanged
{
// 被绑定的后端类,此类继承INotifyPropertyChanged,实现向前端发出属性改变通知。
// 如果没有实现通知功能,后端数据改变后,前端不会刷新。
public event PropertyChangedEventHandler? PropertyChanged;
private string? _name;
public string? Name
{
get { return _name; }
set
{
_name = value;
if(PropertyChanged != null)
{
// 当Name属性改变时,发送属性改变事件,通知前端被绑定的控件刷新数据
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}
}
}