当在同一个对象上绑定大量元素时,当然XMAL也是同样可以绑定,但会使得XMAL的代码量很多,每个绑定的元素都要依此的与控件属性值绑定。为了解决或者改善这个问题。下面介绍这种通用的绑定方式。
1.先看下面的例子
//此处是绑定的数据的类,自己可以自定义此类
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace DataBend
{
public class bnedings : BindableObject
{
private string _serialNum;//私有字段
public string SeriaNum //属性
{
get { return _serialNum; }
set { SetProperty(ref _serialNum, value); }
}
}
public abstract class BindableObject : INotifyPropertyChanged //必须继承INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
protected void SetProperty<T>(ref T item, T value, [CallerMemberName] string propertyName = null)
{
if (!EqualityComparer<T>.Default.Equals(item, value))
{
item = value;
OnPropertyChanged(propertyName);
}
}
}
}
//此处是启动项
public partial class MainWindow : Window
{
bnedings bend = new bnedings();
public MainWindow()
{
InitializeComponent();
grid_sd.DataContext = bend; //数据绑定
}
private void Button_Click(object sender, RoutedEventArgs e)
{
bend.SeriaNum = "我是传递的数据";
}
}
2.下面是前台XMAL
<Window x:Class="DataBend.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:DataBend"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid Name="grid_sd">
<StackPanel>
<TextBox Text="{Binding Path=SeriaNum}" Width="200" Height="30" Background="Red" Margin="3" Foreground="Blue" ></TextBox>
<TextBlock Width="200" Height="30" Background="Blue" Margin="3"></TextBlock>
<Button Content=" Click Me" Width="200" Height="30" Margin="3" Click="Button_Click"></Button>
</StackPanel>
</Grid>
</Window>