سؤال

I am trying to find an elegant way ,how to raise an event when "enterkey" pressed in the keyboard.

in my xaml

<TreeView 
Grid.Row="0" 
Name="Topics"            
VerticalAlignment="Stretch" 
HorizontalAlignment="Stretch" 
MouseDoubleClick="Topics_MouseDoubleClick"
KeyUp="treeViewItem_KeyUp"
ItemsSource="{Binding TierOneItems}"
SelectedItemChanged="treeView1_SelectedItemChanged">

in my xaml.cs

private void treeViewItem_KeyUp(object sender, KeyEventArgs e)
{
    TreeView topic = sender as TreeView;
    string keyValue = e.Key.ToString();
    if (keyValue == "Return")
    {
        //do something here
    }
}

this code works and do the job as expected but looking something different approach from others point of view.

هل كانت مفيدة؟

المحلول

when you are programming in XAML you can make use of behaviors (the declarative way)

first the namespace needed is

xmlns:i="http://schemas.microsoft.com/expression/2009/interactivity"

then your code need to remove the event attached (directly coupled), I tried to rewrite your code for the same

XAML

<TreeView 
...
ItemsSource="{Binding TierOneItems}">
    <i:Interaction.Behaviors>
        <b:RaiseEventBehavior/>
    </i:Interaction.Behaviors>
</TreeView >

RaiseEventBehavior.cs

public class RaiseEventBehavior : Behavior<UIElement>
{
    protected override void OnAttached()
    {
        AssociatedObject.KeyUp += (sender, e) => 
        {
            TreeView topic = sender as TreeView;
            string keyValue = e.Key.ToString();
            if (keyValue == "Return")
            {
             //do something here
            }
        };
    }
}

The above is just an exmple based on your query, feel free to adjust it your on way. This approach is best suited for XAML, leverage behaviors and see the true beauty of XAML

نصائح أخرى

You can use the IsKeyUp method of the Keyboard class to check if a specific key is released.

if (Keyboard.IsKeyUp(Key.Enter))
{
    //do something here
}

Heres how we handle it

    private new void PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return)
        {
            ((SomeVM)this.DataContext).EditSelectedItem();
        }
        else if (e.Key == Key.Delete && this.TreeView.SelectedItem != null &&
            this.TreeView.SelectedItem is DiffVM)
        {
            ((SomeVM)this.DataContext).DeleteDiffV();
        }
     }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top