j.doe
j.doe

Reputation: 35

WPF clickable textblock MVVM

Could you please help me?

I have a checkbox and a text block.

<checkbox ..... /> <textblock ..... />

They are for the ability to remember the password.

How do I make it so that when I click on the text block, the checkbox changes its status.

I can not break the structure of the mvvm pattern.

Upvotes: 0

Views: 2031

Answers (1)

m4a
m4a

Reputation: 187

The easiest way

<CheckBox>
   <TextBlock Text="Your text here"/>
</CheckBox>

Update You should use MVVM. Without mvvm frameworks it will be something like this.

<Window.DataContext>
    <local:ViewModel/>
</Window.DataContext>
...
    <StackPanel>
        <CheckBox Name="CheckBox" IsChecked="{Binding IsChecked, Mode=TwoWay}"/>
        <TextBlock Text="Your text here">
            <TextBlock.InputBindings>
                <MouseBinding Command="{Binding IsCheckedCommand}" MouseAction="LeftClick" />
            </TextBlock.InputBindings>
        </TextBlock>
    </StackPanel>

Code behind

public class RelayCommand : ICommand
{
    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    public RelayCommand(Action<object> execute) : this(execute, null) { }

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        _execute = execute ?? throw new ArgumentNullException(nameof(execute)); _canExecute = canExecute;
    }

    [DebuggerStepThrough]
    public bool CanExecute(object parameter)
    {
        return _canExecute?.Invoke(parameter) ?? true;
    }

    public event EventHandler CanExecuteChanged
    {
        add => CommandManager.RequerySuggested += value;
        remove => CommandManager.RequerySuggested -= value;
    }
    public void Execute(object parameter) { _execute(parameter); }
}

public class ViewModel:INotifyPropertyChanged
{
    public bool IsChecked { get; set; } 

    public RelayCommand IsCheckedCommand { get; set; }

    public ViewModel()
    {
        IsCheckedCommand = new RelayCommand(m => IsCheckedCommandExecute());
    }

    private void IsCheckedCommandExecute()
    {
        IsChecked = !IsChecked;
        OnPropertyChanged(nameof(IsChecked));
    }

    public event PropertyChangedEventHandler PropertyChanged;

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

https://msdn.microsoft.com/en-us/magazine/dd419663.aspx

If you don't want to create custom implementation of ICommand and INotifyPropertyChanged you can take mvvm framework, e.g. MvvmLight

Upvotes: 2

Related Questions