📘 WPF: Zaawansowane Mechanizmy (Przygotowanie do Lab 3)

1. IValueConverter – Logiczna obróbka danych

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}}"/>

2. Komendy (ICommand) – Logika bez Code-Behind

Czym są: Sposobem na odseparowanie działania przycisku od pliku .xaml.cs. Komenda wie, co robić (Execute) i czy można to zrobić (CanExecute).

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;
    }
}

Blokowanie przycisku inaczej:

<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.