splimter
10/19/2019 - 8:27 PM

WPF

WPF Templates

DATA

XAML Binding

<Window.Resources>
    <DataTemplate x:Key="CraftsmanTempalte" DataType="{x:Type local:Craftsman}">
        <StackPanel>
            <TextBlock
                x:Name="Name"
                Text="{Binding name}" />
            <TextBox
                x:Name="Age"
                Text="{Binding age}" />
        </StackPanel>
    </DataTemplate>
</Window.Resources>

Class Binding

// class will implement INotifyPropertyChanged
public int _age;

public int age
{
    get { return _age; }
    set { _age = value; OnPropertyChanged(); }
}

public event PropertyChangedEventHandler PropertyChanged;

[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(
    [CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this,
        new PropertyChangedEventArgs(propertyName));
}

Converter

    class VisibilityChanger : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool actualValue = (bool)value;
            Visibility res = (parameter == null || parameter.ToString() != "inverse")
            ? (actualValue ? Visibility.Visible : Visibility.Hidden)
            : (actualValue ? Visibility.Hidden : Visibility.Visible);
            return res;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }