Abdulsalam Elsharif
Abdulsalam Elsharif

Reputation: 5101

Access Button inside DataTemplate in WPF ItemsControl

I want to access the Button inside MouseDown event, I have the following:

XAML:

<ItemsControlx:Name="icName" MouseDown="icItems_MouseDown" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button x:Name="btnName" Tag="{Binding ItemName}"</Button>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
 </ItemsControl>

C#:

private void icName_MouseDown(object sender, MouseButtonEventArgs e)
    {
       ???
    }

How can I access to the button from ItemsControl MouseDown event

ex: MessageBox.Show(ItemName);

Thanks

Upvotes: 0

Views: 1811

Answers (3)

the.Doc
the.Doc

Reputation: 886

if you don't need access to the button, but only need the item name from the bound item, then personally I would add the handler inside the datatemplate, I'm using a grid below.

<ItemsControl x:Name="icName" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid MouseDown="icItems_MouseDown" />
                    <Button x:Name="btnName" Tag="{Binding ItemName}"</Button>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
 </ItemsControl>

Then you can access your datacontext from within the handler.

    private void icName_MouseDown(object sender, MouseButtonEventArgs e)
    {
       var item = (YourItemType)((FrameworkElement)sender).DataContext;
       var itemName = item.ItemName;
    }

You also don't need the tag at all

Upvotes: 0

mm8
mm8

Reputation: 169200

Please refer to the following sample code.

private void icName_MouseDown(object sender, MouseButtonEventArgs e)
{
    ContentPresenter cp = e.OriginalSource as ContentPresenter;
    if (cp != null && VisualTreeHelper.GetChildrenCount(cp) > 0)
    {
        Button button = VisualTreeHelper.GetChild(cp, 0) as Button;
        //do whatever you want with the Button here...
        if (button != null && button.Tag != null)
            MessageBox.Show(button.Tag.ToString());

    }
}

<ItemsControl x:Name="icName" MouseDown="icName_MouseDown" >
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button x:Name="btnName" Content="Button" IsEnabled="False" Tag="{Binding ItemName}"></Button>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Upvotes: 1

Emad
Emad

Reputation: 3929

You can't handle a click on a group of buttons and know which one is clicked. You should handle the click for each button with the same handler like this:

<Button x:Name="btnName" Tag="{Binding ItemName}"  MouseDown="icItem_MouseDown"></Button>

Then the sender is the calling button:

private void icItem_MouseDown(object sender, MouseButtonEventArgs e)
{
   var btn = sender as Button;
   if(btn!=null)
       MessageBox.Show(btn.Tag);
}

Upvotes: -1

Related Questions