简体   繁体   中英

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.

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, eg MvvmLight

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM