Czym jest: Tłumaczem między Modelem a Widokiem. Używamy go, gdy typ danych w C# nie pasuje bezpośrednio do właściwości w XAML (np. bool w modelu ma sterować kolorem Brush w UI).
public class BoolToColorConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
return (bool)value ? Brushes.Red : Brushes.Transparent;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();
}
<Window.Resources>
<local:BoolToColorConverter x:Key="MyColorConv"/>
</Window.Resources>
<Grid Background="{Binding IsUrgent, Converter={StaticResource MyColorConv}}"/>
Czym są: Sposobem na odseparowanie działania przycisku od pliku .xaml.cs. Komenda wie, co robić (Execute) i czy można to zrobić (CanExecute).
CanExecute zwraca false, przycisk w UI automatycznie stanie siÄ™ szary i nieklikalny.public class RelayCommand : ICommand {
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;
public RelayCommand(Action<object> execute, Predicate<object> canExecute = null) {
_execute = execute; _canExecute = canExecute;
}
public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);
public void Execute(object parameter) => _execute(parameter);
public event EventHandler CanExecuteChanged {
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
}
<Button x:Name="Button" Content="Name" Width="70"
Background="Color" Foreground="White" Click="Function_Click"
IsEnabled="{Binding ElementName=<Nazwa pola ktore musi byc wypelnione>, Path=Text.Length}"/>
Jeśli długość tekstu wynosi 0, WPF interpretuje to jako false i przycisk się blokuje. Jak tylko wpiszesz jedną literę, Length > 0 staje się true.