Adding event handlers to buttons inside a ListBox

Here is a declaration for listbox, ItemsSource set in code behind to a collection of objects.
Datatemplate in the following sample binds FirstName property of the object to the content of the button

<ListBox x:Name=”listbox1″ ItemTemplate=”{StaticResource dt}”/>

and in the resources section we will have a datatemplate declared like this

  <UserControl.Resources>
        <DataTemplate x:Key=”dt”>
            <Button  MouseLeftButtonDown=”Button_MouseLeftButtonDown”
                    Content=”{Binding FirstName}”></Button>
        </DataTemplate>
    </UserControl.Resources>

and the codebehind  we create the handler

private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            (sender as Button).Background = new SolidColorBrush(Colors.Green);
        }

I thought click event should have worked but it doesnt

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s