元素绑定
<StackPanel>
<TextBox x:Name="Tb1" Text="hhh"></TextBox>
<Label Content="{Binding ElementName=Tb1,Path=Text}" ></Label>
</StackPanel>
通过DataContext 绑定
<TextBox x:Name="Tb1" Text="{Binding Name}"></TextBox>
var a = new MainWindowViewModel() { Name = "HHHH" };
DataContext = a;
INotifyPropertyChanged通知客服端值已经发生了变化
var a = new MainWindowViewModel() { Name = "HHHH" };
DataContext = a;
Task.Run(async ()=> {
await Task.Delay(3000);
a.Name = "变更通知";
});
public class MainWindowViewModel:INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propName));
}
}
使用第三方插件进行通知
安装 MvvmLight
public class MainWindowViewModel: ViewModelBase
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
RaisePropertyChanged();
}
}
}
使用Command 点击事件
public class MainWindowViewModel: ViewModelBase
{
private string _name;
public MainWindowViewModel()
{
SaveCommand = new RelayCommand(() => {
Name = "点击事件的变更通知";
});
}
public string Name
{
get { return _name; }
set
{
_name = value;
RaisePropertyChanged();
}
}
public RelayCommand SaveCommand { get; private set; }
}
<Button Content="点击" Command="{Binding SaveCommand}"></Button>