[英]Disable selected checkbox on button click
剛剛開始使用MVVM設計模式,我陷入困境。
當我的應用程序啟動時,我有一個填充了對象名稱列表的treeview
。 我已經設置了IsChecked
Binding,它工作正常。 我正在嘗試設置IsEnabled
綁定。
我希望用戶在他想要的樹視圖中選擇項目,然后單擊三個按鈕之一來執行操作。 單擊時,我希望所選項目保留在樹視圖中,但是被禁用,因此用戶無法對這些項目執行其他操作。
我在應用程序中使用了RelayCommand類。
private ICommandOnExecute _execute;
private ICommandOnCanExecute _canExecute;
public RelayCommand(ICommandOnExecute onExecuteMethod,
ICommandOnCanExecute onCanExecuteMethod)
{
_execute = onExecuteMethod;
_canExecute = onCanExecuteMethod;
}
#region ICommand Members
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter)
{
return _canExecute.Invoke(parameter);
}
public void Execute(object parameter)
{
_execute.Invoke(parameter);
}
#endregion
我的對象模型類使用它
private bool _isEnabled;
public bool IsEnabled
{
get { return true; }
set { _isEnabled = value};
}
然后在我的按鈕方法中我有
if (interfaceModel.IsChecked)
{
//Does Something
MyObjectName.IsEnabled = false;
}
這是我的xaml
<CheckBox IsChecked="{Binding IsChecked}" IsEnabled="{Binding IsEnabled, Mode=TwoWay}">
<TextBlock Text="{Binding MyObjectName}" Margin="5,2,1,2" HorizontalAlignment="Left" />
</CheckBox>
你需要這樣的設置:
// Your ViewModel should implement INotifyPropertyChanged
class ViewModel : INotifyPropertyChnaged
{
private bool _isEnabled;
public bool IsEnabled
{
get { return _isEnabled; }
set
{
_isEnabled = value;
SetPropertyChanged("IsEnabled"); // Add this to your setter.
}
}
// This comes from INotifyPropertyChanged - the UI will listen to this event.
public event PropertyChangedEventHandler PropertyChanged;
private void SetPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged( this, new PropertyChangedEventArgs(property) );
}
}
}
請注意, PropertyChanged
來自於讓ViewModel實現INotifyPropertyChanged
。 要通知用戶界面,您必須提出該事件,並告訴它更改了哪些屬性(通常在setter中 - 見上文)。
或者,如果您不喜歡原始字符串(我個人而言),您可以使用泛型和表達式樹來執行以下操作:
public void SetPropertyChanged<T>(Expression<Func<T, Object>> onProperty)
{
if (PropertyChanged != null && onProperty.Body is MemberExpression)
{
String propertyNameAsString = ((MemberExpression)onProperty.Body).Member.Name;
PropertyChanged(this, new PropertyChangedEventArgs(propertyNameAsString));
}
}
在你的二傳手中你可以說:
public bool IsEnabled
{
set
{
_isEnabled = value;
SetPropertyChanged<ViewModel>(x => x.IsEnabled);
}
}
現在它是強類型的,這有點好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.