Hi, @fatih uyanık. Welcome to Microsoft Q&A.
It is a correct approach to define common commands in the BaseViewModel
and inherit them from the ChildViewModel
, which could reduce duplicate code and improve the maintainability of the program.
Here is a simple example(Assuming it is an MVVM project):
Install CommunityToolkit.Mvvm
via NuGet
BaseViewModel.cs
public class BaseViewModel:ObservableObject
{
public RelayCommand saveCommand { get; set; }
public RelayCommand cancelCommand { get; set; }
public BaseViewModel() {
saveCommand = new RelayCommand(Save);
cancelCommand = new RelayCommand(Cancel);
}
public void Save() {
//TODO Save related services
MessageBox.Show("Save Complete");
}
public void Cancel()
{
//TODO Cancel related services
MessageBox.Show("Cancel Complete");
}
}
MainViewModel.cs(Here as a child ViewModel)
public class MainViewModel:BaseViewModel
{
public MainViewModel():base() {
}
}
MainWindow.xaml
<Grid>
<Grid.DataContext>
<vm:MainViewModel></vm:MainViewModel>
</Grid.DataContext>
<Button Content="Save" Command="{Binding saveCommand}" Width="200" Height="50" ></Button>
<Button Content="Cancel" Command="{Binding cancelCommand}" Width="200" Height="50" Margin="0,200,0,0"></Button>
</Grid>
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.