简体   繁体   中英

Accessing generic sender's properties in a single event (wpf)

I have made a Tree View containing different color names. Each color has it's respective foreground (eg The tree item view having Header="Red" has Foreground="Red" too)

Now, I want to change the background color of the window according to the item the user double clicks on. For example, if User clicks on "Red", the window background turns Red.
Also, I just want to make a single command/ event to do that, so it can be used by all the tree view items' MouseDoubleClick property.

Is there a way to access the item's foreground in code-behind?
I'm trying the following but it's not working:

public void ColorChanger(object sender, MouseButtonEventArgs e)
{   
    this.Background= sender as TreeViewItem.Foreground; 
}

This should work provided that sender is a TreeViewItem :

public void ColorChanger(object sender, MouseButtonEventArgs e)
{
    if (sender is TreeViewItem menuItem)
        this.Background = menuItem.Foreground;
}

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