1、定义包含要绑定属性的类,注意,该类必须继承接口INotifyPropertyChanged类。
2、在需要绑定的属性中触发属性改变事件(PropertyChanged)。
using System;
using System.ComponentModel;
public class Product : INotifyPropertyChanged
{
public Product() { }
public void UpdateProduct(string modelNumber, string modelName, decimal? unitCost, string description)
{
ModelNumber = modelNumber;
ModelName = modelName;
UnitCost = unitCost;
Description = description;
}
private string _ModelNumber;
public string ModelNumber
{
get { return _ModelNumber; }
set
{
if (_ModelNumber != value)
{
_ModelNumber = value;
OnPropertyChanged("ModelNumber");
}
}
}
private string _ModelName;
public string ModelName
{
get { return _ModelName; }
set
{
if (_ModelName != value)
{
_ModelName = value;
OnPropertyChanged("ModelName");
}
}
}
private decimal? _UnitCost;
public decimal? UnitCost
{
get { return _UnitCost; }
set
{
if (_UnitCost != value)
{
_UnitCost = value;
OnPropertyChanged("UnitCost");
}
}
}
private string _Description;
public string Description
{
get { return _Description; }
set
{
if (_Description != value)
{
_Description = value;
OnPropertyChanged("Description");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
定义静态属性,该属性类型即为以上定义类,定义该属性的位置任意。
private static Product _xProduct = new Product();
public static Product xProduct
{
get { return _xProduct; }
}
在xaml文件中将以上定义的静态属性作为源(Source)绑定要指定的元素,路径(Path)指向该属性中的属性。
注意,xProduct在MainWindow类中定义。
<TextBox Grid.Column="1" Margin="5,8,10,4" TextWrapping="Wrap"
Text="{Binding Source={x:Static local:MainWindow.xProduct}, Path=ModelNumber}"/>
<TextBox Grid.Column="1" Margin="5,4,10,4" TextWrapping="Wrap" Grid.Row="1"
Text="{Binding Source={x:Static local:MainWindow.xProduct}, Path=ModelName}"/>
<TextBox Grid.Column="1" Margin="5,4,10,4" TextWrapping="Wrap" Grid.Row="2"
Text="{Binding Source={x:Static local:MainWindow.xProduct}, Path=UnitCost}"/>
<TextBox Grid.ColumnSpan="2" Margin="10,4,10,8" Grid.Row="4" TextWrapping="Wrap"
Text="{Binding Source={x:Static local:MainWindow.xProduct}, Path=Description}"/>