Commands - toligmueller/WPF-MVVM-App-.NET5.0 GitHub Wiki
Commands bzw. "RelayCommand" werden verwendet um von der Views aus Befehle an das ViewModel zu senden.
Für eine nahtlose Implementation in WPF werden wir Microsoft.Toolkit.Mvvm.Input durch Microsoft.Toolkit.Mvvm.Input.Wpf ersetzen, da wir da den "CommandManager" nachrüsten .
<Window x:Class="Beispiel.Views.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainViewWindow"
Height="300"
Width="300">
<Grid>
<Button Context="OK" Command={Binding OkCmd}/>
</Grid>
</Window>using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input.Wpf;
namespace Beispiel.Viemodels
{
public class BeispielViewModel
{
public RelayCommand OkCmd => new(
() =>
{
// Auszuführender Code
},
() => true // bool Bedingung ob der Command und das gebundene Element ausführbar sind
);
}
}Async
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input.Wpf;
namespace Beispiel.Viemodels
{
public class BeispielViewModel
{
public AsyncRelayCommand OkCmd => new(
async () =>
{
// Auszuführender Code
},
() => true // bool Bedingung ob der Command und das gebundene Element ausführbar sind
);
}
}<Window x:Class="Beispiel.Views.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainViewWindow"
Height="300"
Width="300">
<Grid>
<Button Context="OK" Command={Binding OkCmd} CommandParameter="String"/>
</Grid>
</Window>using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input.Wpf;
using Microsoft.Xaml.Behaviors;
namespace Beispiel.Viemodels
{
public class BeispielViewModel
{
public RelayCommand<string> OkCmd => new(
param =>
{
// Auszuführender Code
// "param" enhält den Wert der mit "CommandParameter" übergeben wurde
},
param => true // bool Bedingung ob der Command und das gebundene Element ausführbar sind
);
}
}Hier nötigen wir das NuGet-Package: Microsoft.Xaml.Behaviors.Wpf
<Window x:Class="Beispiel.Views.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
Title="MainViewWindow"
Height="300"
Width="300">
<Grid>
<Label Context="OK">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding OkCmd}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Label>
</Grid>
</Window>using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input.Wpf;
using Microsoft.Xaml.Behaviors;
namespace Beispiel.Viemodels
{
public class BeispielViewModel
{
public RelayCommand OkCmd => new(
() =>
{
// Auszuführender Code
},
() => true // bool Bedingung ob der Command und das gebundene Element ausführbar sind
);
}
}