繁体   English   中英

如何处理自定义控件中的事件?

[英]How do I handle events in a custom control?

我有一个像这样的自定义ItemsControl

public class MyControl : ItemsControl { }

我的模板会像

<Style TargetType="{x:Type local:MyControl}">
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBox Text="{Binding Text}" /> 
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

现在我想在按下ENTERSPACE时采取行动,所以我会做这样的事情

<TextBox Text="{Binding Text}">
    <TextBox.InputBindings>
        <KeyBinding Key="Space" 
                    Command="{Binding KeyPressedCommand}" 
                    CommandParameter="{x:Static Key.Space}"/>
    </TextBox.InputBindings>
</TextBox>

但是我如何将它绑定到我的控件?

解决它的方法之一是使用教程中的MVVM 模式和RelayCommand类。

中继命令.cs

public class RelayCommand : ICommand
{
    private readonly Action<object> _execute;
    private readonly Func<object, bool> _canExecute;

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
    public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);
    public void Execute(object parameter) => _execute(parameter);
}

然后你应该设置你的Window(或UserControl)的DataContext ,它需要解析xaml中的绑定。

这样做的方法之一:

主窗口.xaml

<Window.DataContext>
    <local:MainViewModel/>
</Window.DataContext>

MainViewModel类中的“类似这样的”示例设置Text属性和KeyPressedCommand

主视图模型.cs

public class MainViewModel : INotifyPropertyChanged
{
    private bool _text;
    public bool Text
    {
        get => _text;
        set
        {
            _text = value;
            OnPropertyChanged(nameof(Text));
            // Text changed!
        }
    }
    public ICommand KeyPressedCommand => new RelayCommand(obj =>
    {
        if (obj is Key key) {
            // do something here with the 'key' provided by CommandParameter
        }
    });

    public MainViewModel()
    {
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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