Как вызвать событие KeyUp в MVVM с помощью ICommand - PullRequest
1 голос
/ 07 января 2020

Я создал этот простой вид:

enter image description here

Теперь, когда я нажимаю клавишу RETURN, когда курсор находится внутри одного из этих 2 текстовых полей, я хочу, чтобы кнопка "Suchen" = SEARCH вызывала (KeyUp Event).

Я знаю, как легко сделать это в коде, но я хочу сделать это в MVVM (в моем классе модели представления) с помощью ICommand , В приведенном ниже коде я использовал (автоматически сгенерированный) параметр KeyEventArgs.

Я пробовал его в MVVM с использованием ICommand, но метод Command выдает ошибку, утверждая, что мне потребуется создать экземпляр объекта для аргумента KeyEventArgs. В коде (не похожем на mvvm) мне не нужно ничего создавать, поскольку параметр KeyEventArgs был «автоматически сгенерирован», как и метод. Так что мне не пришлось об этом беспокоиться.

Как заставить событие KeyUp работать в моем проекте MVVM? Для ответа на этот вопрос я предоставляю вам следующий сокращенный код:

Просмотр XAML:

 <StackPanel Height="423" VerticalAlignment="Bottom">
        <Label Name="lblArtikelbezeichnung" Content="Artikelbezeichnung:" Margin="20, 20, 20, 0"></Label>
        <TextBox Name="txtArtikelbezeichnung" 
                 Width="Auto" 
                 Margin="20, 0, 20, 0"
                 IsEnabled="{Binding BezEnabled}"
                 Text="{Binding BezText}">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="TextChanged">
                    <i:InvokeCommandAction Command="{Binding TextChangedBez}" />
                </i:EventTrigger>
                <i:EventTrigger EventName="KeyUp">
                    <i:InvokeCommandAction Command="{Binding KeyUpBez}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </TextBox>
        <!--TextChanged="txtArtikelbezeichnung_TextChanged" 
                 KeyUp="txtArtikelbezeichnung_KeyUp"-->
        <Label Name="lblLieferant" Content="Lieferant:" Margin="20, 0, 20, 0"></Label>
        <TextBox Name="txtLieferant" 
                 Width="Auto" 
                 Margin="20, 0, 20, 0"
                 IsEnabled="{Binding LiefEnabled}"
                 Text="{Binding LiefText}">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="TextChanged">
                    <i:InvokeCommandAction Command="{Binding TextChangedLief}" />
                </i:EventTrigger>
                <i:EventTrigger EventName="KeyUp">
                    <i:InvokeCommandAction Command="{Binding KeyUpLief}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </TextBox>
            <!--TextChanged="txtLieferant_TextChanged" 
                 KeyUp="txtLieferant_KeyUp"-->
        <Button Name="btnSuchen" 
                Content="Suchen" 
                Width="100" Height="25" 
                Margin="20, 10,240, 10" 
                Command="{Binding GefilterteSuche}">
        </Button>
...
<StackPanel>

Код сзади:

    using System.Windows;

    namespace Lieferscheine
    {
        /// <summary>
        /// Interaktionslogik für artikelHinzu.xaml
        /// </summary>
    public partial class artikelHinzu : Window
    {

        public artikelHinzu()
        {
            InitializeComponent();
            DataContext = new ArtikelHinzuViewModel();
        }     
    }
}

Просмотр модели:

    public class ArtikelHinzuViewModel : INotifyPropertyChanged
    {              
//ICommands (shortened)
        public ICommand GefilterteSuche => new DelegateCommand<object>(SucheArtikel);                     
        public ICommand KeyUpLief => new DelegateCommand<KeyEventArgs>(KeyUpLieferant);       
        public ICommand KeyUpBez => new DelegateCommand<KeyEventArgs>(KeyUpBezeichnung);

 //INotifyPropertyChanged      
        public event PropertyChangedEventHandler PropertyChanged;
        public virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        //Konstruktor
        public ArtikelHinzuViewModel()
        {

        }

//ICommand methods (shortened for reasons of simplicity)        

         //KeyUp Events (THIS PART IS MY PROBLEM)      
        private void KeyUpBezeichnung(KeyEventArgs e) //the argument is obligatory but it does not have an instantiated object which is why an error fires...
        {
//since I need to create an object for KeyEventArgs I tried this but it is useless...
        /*e = new KeyEventArgs(Keyboard.PrimaryDevice,
        Keyboard.PrimaryDevice.ActiveSource,
        0, Key.Back);
//I need to access this e.Key property but don't know how in my case! That is the actual problem...
            if (e.Key == Key.Return)
            {
                object o = new object();
                SucheArtikel(o);
            }
            */
        }
//same problem here as above...
        private void KeyUpLieferant(KeyEventArgs e)
        {
            /*
        e = new KeyEventArgs(Keyboard.PrimaryDevice,
        Keyboard.PrimaryDevice.ActiveSource,
        0, Key.Back);

            if (e.Key == Key.Return)
            {
                object o = new object();
                SucheArtikel(o);
            }
             */
        }

    }

1 Ответ

2 голосов
/ 08 января 2020

Использование InputBindings проще:

<TextBox>
    <TextBox.InputBindings>
        <KeyBinding Key="Enter" Command="{Binding SearchCommand}" />
    </TextBox.InputBindings>
</TextBox>
...