简体   繁体   中英

Assigning a value to my view model from my dependency property from xaml in a user control

I need to capture a key press event to get the key value from my custom DataGrid `public class ExtendedDataGrid : DataGrid {} and have it fire an event in my view model with the Key that was pressed. To be precise, I want to check if someone pressed the Delete key and then delete a record from the currently selected without using code behind because all of my logic is in my view model.

My ExtendedDataGrid control is new and I have created a collection of GridColumns (My own class definition) that sets the columns from the view model and that works where the view model sends the value to the DependencyProperty. However, this time I want to capture the keyboard input from PreviewKeyDown and send it to the view model.

I created a method in my ExtendedDataGrid class and placed in the constructor : PreviewKeyDown += OnKeyDown ; This fires the event as expected. I created a DependencyProperty :

public static readonly DependencyProperty KeyDownValueProperty =
    DependencyProperty.Register("KeyDownValue", typeof(Key), typeof(ExtendedDataGrid), null, null);

I then created a method :

    private void OnKeyDown(object Sender, KeyEventArgs Args)
    {
        SetValue(KeyDownValueProperty, Args.Key);
    }

I then declared the property wrapper:

    [Bindable(true)]
    public Key KeyDownValue
    {
        get
        {
            return (Key)GetValue(KeyDownValueProperty);
        }

        set
        {
            SetValue(KeyDownValueProperty, value);
        }
    }

The last thing I did was to add in XAML, KeyDownValue="{Binding Path=KeyThatWasPressed}". This is declared as a public property in my view model of type Key.

I was hoping that the pressing of the key would fire the event I created, which it does, and then send the value to the Dependency Property and have it notify the change/value in my view model, which it does not.

Once I get this then all else will fall into place, as I am a quick learner. I am simply missing some basics here. Any help would be greatly. Once I have learned enough I may well start answering other newbie questions on this subject.

当您将VM绑定到ExtendedDataGrid时,请尝试将绑定模式设置为TwoWay

KeyDownValue="{Binding Path=KeyThatWasPressed, Mode=TwoWay}"

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