技术学习

我所喜欢的

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

有一个比较重要的点就是,继承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>

  

单击按钮发现值随之更改!!!

posted on 2025-03-19 21:59  飘扬De黑夜  阅读(24)  评论(0)    收藏  举报