How to get CommunityToolkit.Mvvm to work in .NET 9


The way for old WPF apps was using MVVMLight library by Laurent Bugnion.

Now I am trying to get WPF to work in a modern .NET 9 world. I am trying to get the CommunityToolkit.Mvvm package (aka MVVM Toolkit, formerly named Microsoft.Toolkit.Mvvm) at Community MVVM to work, but I am having trouble with the data binding to commands to display a screen.  The latest incarnation does not appear to have BaseViewModels or ViewModelLocators.

The documentation part to get this to work is likely the RelayCommand page.  My core problem is likely setting the DataContext="{Binding Source=vm:MainWindowViewModel}" of the Main Window's xaml so it links.

I need to look through a Sample App I found to ensure my bindings and visibilities are correct.


UPDATE - Got commands working to the View Model. Attempting to set the DataContext to the VM on the Window failed.

Main Window:

<Window x:Class="CodeGen.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:CodeGen"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:md="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:vm="clr-namespace:CodeGen.ViewModel"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Style="{StaticResource MaterialDesignWindow}"
mc:Ignorable="d"
Title="{Binding Title}" Height="450" Width="800"
d:DataContext="{d:DesignInstance Type=vm:MainWindowViewModel}">

<Page>
<Page.DataContext>
      <vm:MainWindowViewModel x:Name="ViewModel"/>
</Page.DataContext>

<Grid>
   <Grid.RowDefinitions>
      <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

<DockPanel>
<Menu DockPanel.Dock="Left" HorizontalAlignment="Left">
     <MenuItem Header="Connect" Command="{Binding ConnectCommand}" ToolTip="Database Connect" InputGestureText="Ctrl+C">
         <MenuItem.Icon>
             <md:PackIcon Kind="Connection"/>
         </MenuItem.Icon>
   </MenuItem>
</Menu>
</DockPanel>

</Grid>
</Page>
</Window>

View Model:

public class MainWindowViewModel : ObservableObject, INotifyPropertyChanged
{
     public MainWindowViewModel() { ConnectCommand = new RelayCommand(OnConnect, CanConnect); }
     public RelayCommand ConnectCommand { get; }
     private void OnConnect() { throw new NotImplementedException(); }
     private bool CanConnect() { return true; }
}







Comments

Popular posts from this blog

Upgrading to .NET8 from desktop versions 4.8.X

JSON Web Tokens

GHL > Set website so shorter URL address