当我使用RelayCommand

时间:2019-01-29 20:02:37

标签: c# .net wpf mvvm data-binding

我目前正在尝试使用MVVM处理多个视图和视图模型,并且设法设置了默认视图,并且我想在单击绑定到命令的按钮时更改视图。

该命令将触发并执行应替换视图的代码,但由于某种原因,它不是,而且我不知道为什么。

所以我的MainWindows.xaml看起来像这样

<Grid Column="0"
              Background="Gray">

            <StackPanel>
                <Button Height="50"
                        Content="Home"/>

                <Button Height="50"
                        Content="Add"
                        Command="{Binding DisplayAddViewCommand}"/>
            </StackPanel>
        </Grid>

        <ContentControl Grid.Column="1"
                        Content="{Binding CurrentView}"/>

如您所见,有两个按钮和一个ContentControl绑定到属性CurrentView

我还将窗口的DataContext设置为BaseViewModel

<Window.DataContext>
    <viewModels:BaseViewModel/>
</Window.DataContext>

如果我们看一下BaseViewModel,我们可以看到CorrentView在构造函数中被设置为HomeVM,这很好,它从HomeView开始,但是当我单击绑定到您看到的命令的按钮时在那里,它触发了CurrentView = AddVM,但实际上并没有改变视图,也没有更新视图。

public class BaseViewModel : ObservableObject
    {
        public RelayCommand DisplayAddViewCommand { get; set; }
        public object CurrentView { get; set; }
        public HomeViewModel HomeVM { get; set; }
        public AddViewModel AddVM { get; set; }

        public BaseViewModel()
        {
            HomeVM = new HomeViewModel();
            AddVM = new AddViewModel();

            CurrentView = HomeVM;

            DisplayAddViewCommand = new RelayCommand(o => DisplayAdd(), o => true);
        }

        public void DisplayAdd()
        {
            CurrentView = AddVM;
        }

    }

这是我显示模型的方式

<Application.Resources>
    <DataTemplate DataType="{x:Type viewModels:HomeViewModel}">
        <views:HomeView/>
    </DataTemplate>

    <DataTemplate DataType="{x:Type viewModels:AddViewModel}">
        <views:AddView/>
    </DataTemplate>
</Application.Resources>


public class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

命令本身没有错,因为它命中了断点,而我已经逐步执行了,并且对象继承自的ObservableObject也很好。

0 个答案:

没有答案
相关问题