1

I want to implement my navigation in my WPF application. Currently the StartScreen.xaml is shown on startup, but when I click on the button the DeviceManagement.xaml is not shown. Not even the ShowDeviceManagement command is called.

This let me assume that the Command of the Button is not correct? How can I fix it?

App.xaml

<Application.Resources>
    <DataTemplate DataType="{x:Type vm:DeviceManagementViewModel}">
        <view:DeviceManagement />
    </DataTemplate>

    <DataTemplate DataType="{x:Type vm:MainWindowViewModel}">
        <view:StartScreen />
    </DataTemplate>
</Application.Resources>

MainWindow.xaml

<Window ...>
    <Window.DataContext>
        <vm:MainWindowViewModel/>
    </Window.DataContext>
    <ContentControl
        Content="{Binding ViewModel}">
    </ContentControl>
</Window>

StartScreen.xaml

<UserControl ...>
     <Button
         Content="Click Me"
         Command="{Binding DataContext.ShowDeviceManagement, RelativeSource={RelativeSource AncestorType={x:Type vm:MainWindowViewModel}}, Mode=OneWay}"/>
</UserControl>

MainWindoViewModel.cs

class MainWindowViewModel : ViewModelBase
{
    public ViewModelBase ViewModel { get; set; }

    public MainWindowViewModel()
    {
        ViewModel = this;
    }

    public ICommand ShowDeviceManagement
    {
        get
        {
            return new RelayCommand(action => ViewModel = new DeviceManagementViewModel());
        }
    }
}

1 Answer 1

1

"DataContext" is obsolete in your command binding. RelativeSource is used to find ancestor in visual tree, and your MainWindowViewModel is not Visual. Should be like this:

Command="{Binding ShowDeviceManagement, Mode=OneWay}"
Sign up to request clarification or add additional context in comments.

1 Comment

Try to initialize your RelayCommand and set it to private field in the constructor and in ShowDeviceManagement property just return this field, instead of creating command instance each time the property accessed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.