Linda_Leica

I have a TreeView and need to put a button before every TreeViewItem. I defined the treeview style in a separate resource file. How can I associate this button click event with TreeViewItem mouse event
Thanks a lot.


Another problem is: during selection, if the treeView container lost focus and gain focus again, SelectedItemChanged event will be fired twice, the first time is right. Second time its parent will be selected. Any idea Thanks.


Re: Windows Presentation Foundation (WPF) How to add button click event when Button is defined in a style?

dvsdata

Hi, don't know whether my solution fits your needs. I had a similar situation where I had to handle the Click event of a Button defined in a DataTemplate. What I did was: add a code-behind class to ResourceDictionary where the DataTemplate (should work with styles as well) is defined. In the XAML declaration of the button provide a callback for the Click event and implement it in the code-behind class. In the callback, you receive the originating button instance as an argument; you can use it in order to navigate through the hierarchy of controls.

Here is an example in code of how things would look like in your case:-

<!-- MyResourceDictionary.xaml -->
<ResourceDictionary x:Class="MyNamespace.MyResourceDictionary" ... >
...
<Style TargetType="{x:TypeTreeViewItem}">
...
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TreeViewItem}">
...
<Grid>
<Grid.ColumnDefinitions>
...
</Grid.ColumnDefinitions>

<Button Name="myButton" Grid.Column="0" Click="OnMyButtonClicked"/>
<TextBox Name="myTextBox" Grid.Column="1"/>
</Grid>
...
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
...
</ResourceDictionary>




//MyResourceDictionary.xaml.cs

using ...

namespace MyNamespace
{
public partial class MyResourceDictionary: ResourceDictionary
{
public MyResourceDictionary()
{
InitializeComponent();
}

private void OnMyButtonClicked(object sender, EventArgs args)
{
Button b = (Button) sender;
Grid g = (Grid)b.Parent;
TextBox tb = null;
foreach (UIElement element in g.Children)
{
if (element is TextBox)
{
tb = (TextBox)element;
//you may check tb.Name == "myTextBox" to be sure...
break;
}
}

if (tb != null)
{
//do something with tb...
}
}

...
}
}

Hope this helps.





Re: Windows Presentation Foundation (WPF) How to add button click event when Button is defined in a style?

FraserKp

This solution worked nicely for me too - I managed to simplify the textbox finding code though.

If you do assign a name the component you want to lookup, then where you are casting to a button from the sender parameter just use the FindName method to get it. Saves writing all that looping code and means that you don't have to rely on the thing you looking for being in a the same grid as you (or a grid at all).