3

MVVM 設計パターンを使い始めたばかりで、行き詰まっています。

アプリケーションが起動するtreeviewと、オブジェクト名のリストが取り込まれます。IsCheckedバインディングをセットアップしましたが、正常に動作します。IsEnabledバインディングをセットアップしようとしています。

ユーザーが必要なツリービューでアイテムを選択し、3 つのボタンのいずれかをクリックしてアクションを実行するようにします。クリックすると、選択したアイテムがツリービューに残りますが、無効になり、ユーザーはそれらのアイテムに対して別のアクションを実行できなくなります。

アプリケーションで 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>
4

1 に答える 1

2

次のような設定が必要です。

// 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) );
        }
    }
}

PropertyChangedViewModel を実装することに注意してくださいINotifyPropertyChanged。UI に通知するには、そのイベントを発生させ、どのプロパティが変更されたかを通知する必要があります (通常はセッターで - 上記を参照)。

または、生の文字列が気に入らない場合 (個人的には好きではありません)、ジェネリックと式ツリーを使用して次のようなことを行うことができます。

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);  
    }
}

そして今、それは強く型付けされています。これはちょっといいことです。

于 2013-10-07T16:03:53.623 に答える