【问题标题】:wpf mvvm binding change textBlock text [duplicate]wpf mvvm绑定更改textBlock文本[重复]
【发布时间】:2021-07-25 16:06:01
【问题描述】:

我有一个文本块,我想通过他的绑定属性将其从 false 变为 true。 该属性已更改为 true,但文本框的文本保持为 false。 我怎样才能做到这一点。 感谢您的帮助。

    <TextBlock x:Name="resBlock" Grid.Row="3" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="250" Height="50" Text="{Binding Source={StaticResource Locator}, Path=Main.Result}" TextAlignment="Center" FontSize="30" />
    public class MainViewModel : ViewModelBase
    {
        public MainViewModel()
        {
            LoginCommand = new RelayCommand(Login);
            user = new User();
        }
        DataService service = new DataService();
        public User user { get; set; }
        public bool Result { get; set; }
    
        public ICommand LoginCommand { get; }
    
        public async void Login()
        {
            Result = await service.LoginAsync(user); // get True
        }
    }

【问题讨论】:

    标签: c# wpf xaml mvvm


    【解决方案1】:

    要更改视图模型的控制量,您必须实现INotifyPropertyChanged 接口。

    将 MainViewModel 更改为:

    public class MainViewModel : ViewModelBase, INotifyPropertyChanged
    {
       public MainViewModel()
       {
          LoginCommand = new RelayCommand(Login);
          user = new User();
       }
       DataService service = new DataService();
       public User user { get; set; }
        
       public ICommand LoginCommand { get; }
        
       public async void Login()
       {
           Result = await service.LoginAsync(user); // get True
       }
       private bool result;
    
       public bool Result
       {
          get { return result; }
          set
          {
              result = value;
              OnPropertyChange(nameof(Result));
          }
       }
    
       public event PropertyChangedEventHandler PropertyChanged;
    
       protected void OnPropertyChange(string propertyName)
       {
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-15
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 2013-04-04
      • 1970-01-01
      • 2015-10-16
      • 2011-01-01
      • 2012-11-24
      相关资源
      最近更新 更多