写一个抽象类通用于绑定
public abstract class NotificationObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
写一个viewmodel(用了mvvm模式)
PS:这里很关键,RaisePropertyChanged函数里面这个字符串名称要和viewmodel这个属性名一样,不能和xmal的名称一样
public class MainWindowViewModel : NotificationObject
{
public MainWindowViewModel()
{
mainWindowModel = new MainWindowModel();
}
public MainWindowModel mainWindowModel;
public string PLCConnect
{
get
{
return mainWindowModel.PLCConnect;
}
set
{
mainWindowModel.PLCConnect = value;
RaisePropertyChanged("PLCConnect");
}
}
}
后台
private MainWindowViewModel mainWindowViewModel;
public void Window_Loaded(object sender, RoutedEventArgs e)
{
mainWindowViewModel = new MainWindowViewModel();
DataContext = mainWindowViewModel;
}
前台
<Label x:Name="sqlLabel" Content="{Binding SQLConnect}" Margin="76,207,0,0"/>
之后修改数据前台就能更改
mainWindowViewModel.PLCConnect = "更改第一次";