有一个比较重要的点就是,继承INotifyPropertyChanged,并实现OnPropertyChanged。
viewModel实现代码如下:
public class MainWindowViewModel:INotifyPropertyChanged
{
    private bool _isBinding = false;
    public bool IsBinding
    {
        get
        {
            return _isBinding;
        }
        set
        {
            this._isBinding = value;
            OnPropertyChanged("IsBinding");
            // 通知UI界面更新绑定BindingText值的控件进行数据更新
            OnPropertyChanged("BindingText");
        }
    }
    public string BindingText
    {
        get
        {
            return this.IsBinding ? "绑定" : "空闲";
        }
    }
    private string _bindingName="MyBindingName";
    public string BindName 
    { 
        get
        {
            return _bindingName;
        }
        set
        {
            this._bindingName = value;
            OnPropertyChanged("BindName");
        } 
    }
    public event PropertyChangedEventHandler? PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
窗体后台代码如下:
public partial class MainWindow : Window
{
    public MainWindowViewModel ViewModel {  get; set; } = new MainWindowViewModel();
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = ViewModel;
    }
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        this.ViewModel.BindName = "更改";
    }
}
xaml前端代码如下:
 <StackPanel>
     <TextBlock Text="{Binding BindName}" Height="30" Width="220" Background="Aquamarine" />
     <ToggleButton x:Name="MySwitch" IsChecked="{Binding IsBinding}" Content="OFF" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="50" Style="{StaticResource SwitchStyle}"/>
     <Button Content="Button" Height="55" Click="Button_Click"/>
 </StackPanel>
单击按钮发现值随之更改!!!
 
                    
                     
                    
                 
                    
                 
 
         
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号