Pregunta

Here im having,

    private ICommand AddCommand = new RCommand(p => true, p => Add() );
    private void Add()
    {
        emp = new Employee();
        DetailsEntryGrid.DataContext = emp;

        EnableControls();
        tBoxID.Focus();
        tBoxID.SelectAll();
        //throw new NotImplementedException();
    }

vs2010 throws compile time error that 'p' cannot point to a non-static field, and i cannot access the Grid and textbox ..those controls are wpf.. i cannot create object for employee also..

and the Rcommand Class is..

public class RCommand : ICommand
{
    readonly Predicate<object> _CanExecute;
    readonly Action<object> _Execute;
    public RCommand(Action<object> exe) : this(null,exe)
    {

    }

    public RCommand(Predicate<object> predicate, Action<object> action)
    {
        if (predicate == null)
            throw new ArgumentNullException("execute must be provided");
        _Execute = action;
        _CanExecute = predicate;

    }

    public bool CanExecute(object parameter)
    {
        return _CanExecute == null ? true : _CanExecute(parameter);

    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _Execute(parameter);

    }
}

i want to access that Add() method, which inturn i want to access the textbox and datagrids.. how should i.?

or how i should have the RCommand Class..?

¿Fue útil?

Solución

Just move the initialisation to the constructor of your class:

public MyClass()
{
    // other initialisation stuff
    AddCommand = new RCommand(p => true, p => Add() );
}

From your comment - if this is MVVM then you shouldn't be accessing elements on your view in your view model. That increases the coupling between the classes and is a "bad thing".

If you need to change values on the view then you should be using binding.

If you want to do things like change the focus and select all the text in a text box then you should fire an event from the view model and handle it in the view were you will have access to the text box.

In your view model you define an event:

public event EventHandler<MyEventArgs> MyEvent;

Then you fire that event when whatever you want to react to has happened:

if (this.MyEvent != null)
{
    this.MyEvent(this, new MyEventArgs(...));
}

where ... is replaced by the values (if any) you need to pass in your event.

In your view constructor you subscribe to this event:

this.viewModel.MyEvent += MyEventHandler;

It's OK that the view has a reference to the view model, but not the other way round.

The handler is:

private void MyEventHandler(object sender, MyEventArgs e)
{
    // Do your stuff
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top