Привязка WPF не работает с ICommand - PullRequest
0 голосов
/ 19 мая 2018

У меня есть окно с таблицей (DataGrid), открывающее новое окно после двойного щелчка по строке.Я использую MouseBinding: MouseAction="LeftDoubleClick" Command="{Binding MouseDoubleClickCommand}

SelectedSubject при ExecuteCurrentObjectCommand функция верна и DataContext выглядит как установленная при отладке.

class ApplicationViewModel : INotifyPropertyChanged
{        
    private List<Subject> sub = Subject.GetSubjects();

    public ObservableCollection<Subject> Subjects { get; set; }

    private Subject selectedSubject;
    public Subject SelectedSubject
    {
        get { return selectedSubject; }
        set
        {
            selectedSubject = value;
            OnPropertyChanged("selectedSubject");
        }
    }

    public ApplicationViewModel()
    {
        Subjects = new ObservableCollection<Subject>(sub);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged([CallerMemberName] string prop = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(prop));
    }

    private RelayCommand mouseDoubleClickCommand;
    public ICommand MouseDoubleClickCommand
    {
        get
        {
            if (mouseDoubleClickCommand == null)

                mouseDoubleClickCommand = new RelayCommand(ExecuteCurrentObjectCommand,
                    CanExecuteCurrentObjectCommand);

            return mouseDoubleClickCommand;
        }
    }

    private bool CanExecuteCurrentObjectCommand(object obj)
    {
        return SelectedSubject == null ? false : true;
    }

    private void ExecuteCurrentObjectCommand(object obj)
    {
        var oEW = new InfoWindow();
        var vm = new InfoViewModel();
        vm.SelectedObject = SelectedSubject;
        oEW.DataContext = vm;
        oEW.Show();
    }
}

InfoViewModel classсодержит только поле SelectedObject (с функциями get / set).InfoWindow наследуется Window и выполняется только InitializeComponent().

Я также создаю RelayCommand class.

class RelayCommand : ICommand
{
    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");
        _execute = execute;
        _canExecute = canExecute;
    }
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute.Invoke(parameter);
    }
    public event EventHandler CanExecuteChanged
    {
        ...
    }
    public void Execute(object parameter)
    {
        _execute.Invoke(parameter);
    }
}

InfoWindow.xaml код

<Window.Resources>
    <local:Subject x:Key="MSource" />
</Window.Resources>
    <StackPanel Grid.Row="0" Orientation="Horizontal">
        <Label Content="Name:"/>
        <Label Content="{Binding Name, Source={StaticResource MSource}}"></Label>
    </StackPanel>

Новое окно создано, но привязка не работает.В чем проблема?

public class Subject : INotifyPropertyChanged
{
    private int _id;

    public int Id
    {
        get => _id;
        set
        {
            _id = value;
            OnPropertyChanged("Id");
        }
    }

    private string _name;

    public string Name
    {
        get => _name;
        set
        {
            _name = value;
            OnPropertyChanged("Name");
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName]string prop = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(prop));
    }
}

1 Ответ

0 голосов
/ 19 мая 2018

InfoViewModel объект был присвоен DataContext неверно.В xaml я удалил ресурсы и изменил привязку.

<Label Content="{Binding Name}"></Label>

Правильное назначение:

oEW.DataContext = vm.SelectedObject;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...