如何用mvvm禁用文本块?
如何用mvvm禁用文本块?
我是用IsEnabled="{Binding IsEnable}"
尝试的这个架构的新手,即:
XAML:
ViewModel.cs:
public bool IsEnable { get; set; } //constarctor public ViewModel() { IsEnable = false; }
但这并没有什么作用
您需要在代码中设置datacontext:
public partial class MainWindow : Window { public MainWindow () { InitializeComponent(); this.DataContext = new ViewModel(); } }
或者,或者,在XAML中创建viewmodel:
除此之外:我认为您希望您的页面对ViewModel中的更改做出反应。 因此,您需要在viewmodel中实现INotifyPropertyChanged
,如下所示:
public class ViewModel: INotifyPropertyChanged { private string _isEnabled; public string IsEnabled { get { return _isEnabled; } set { if (value == _isEnabled) return; _isEnabled= value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
如果模型的值发生更改,则INotifyPropertyChange会“更新”您的UI。
Heyho,您应该像以下示例一样实现INotifyPropertyChanged
:
public class ViewModel : INotifyPropertyChanged { private bool _isEnabled; public bool IsEnabled { get { return _isEnabled; } set { if (_isEnabled != value) { _isEnabled = value; OnPropertyChanged("IsEnabled"); } } } #region INotify #region PropertyChanged /// /// PropertyChanged event handler /// public event PropertyChangedEventHandler PropertyChanged; #endregion #region OnPropertyChanged /// /// Notify the UI for changes /// public void OnPropertyChanged(string propertyName) { if (string.IsNullOrEmpty(propertyName) == false) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } #endregion #endregion }
问候,
k1ll3r8e