簡體   English   中英

WPF 可點擊文本塊 MVVM

[英]WPF clickable textblock MVVM

請你幫助我好嗎?

我有一個復選框和一個文本塊。

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

它們是為了能夠記住密碼。

我如何做到這一點,以便當我單擊文本塊時,復選框會更改其狀態。

我無法打破 mvvm 模式的結構。

最簡單的方法

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

更新您應該使用 MVVM。 如果沒有 mvvm 框架,它將是這樣的。

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

背后的代碼

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

如果您不想創建 ICommand 和 INotifyPropertyChanged 的​​自定義實現,您可以采用 mvvm 框架,例如 MvvmLight

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM