WPF Binding表达式
前言:
WPF BindingBinding表达式的使用,可以很方便的绑定参数和更新界面数据。
1.界面添加控件,并设置对应属性的Binding表达式,例如:
<Window x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<TextBlock FontSize="18">请扫码:</TextBlock>
<TextBox MinWidth="200" Height="252" Margin="2" Text ="{Binding BarID}"></TextBox>
</StackPanel>
</Grid>
</Window>
2.编写Binding类,例如:
public class MainUI : INotifyPropertyChanged
{
private string _BarID;
public string BarID
{
get { return _BarID; }
set
{
_BarID = value;
if (PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("BarID"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
3.当前界面赋值给这个Binding类:
3.1实例化Binding类:
MainUI mainUI = new MainUI();
3.2,界面赋值:
this.DataContext = mainUI;
3.3 调用:
mainUI.BarID = "123";
此时界面上的TextBox 同样显示“123”。