cpoDesign
cpoDesign

Reputation: 9153

How to Identify button for list item

How do i access the object UserNames, that is bound to the list??

What i did so far:

Item of the list is object in my case:

 new List<UserNames>();
 this.users.Add(new UserNames() {Id = 1, UserName = "name 1"});

I am using data template for which i have label and button.

My List is as follows:

<ListBox Grid.Column="1" Grid.Row="1" Name="listBox1" ItemsSource="{Binding}" SelectedValuePath="Id">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <WrapPanel Orientation="Vertical">
                        <StackPanel>
                            <Label Content="{Binding UserName}"  />
                        </StackPanel>
                        <StackPanel Name="ButtonStackPanel">
                            <Button Name="MyButton" Content="Click Me" Click="MyButton_Click">

                            </Button>
                        </StackPanel>
                    </WrapPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

Where my method for Button is. As you can see i did try to utilise the parent option, but without sucess

 private void MyButton_Click(object sender, RoutedEventArgs e)
        {
            //StackPanel panel = (StackPanel)((Button)sender).Parent;
            //WrapPanel wrapPanel = (WrapPanel) panel.Parent;
            //ListItem listItem = (ListItem) wrapPanel.Parent;
            //ListBox box = (ListBox) listItem.Parent;
            //UserNames itemToReport = (UserNames) (box.SelectedItem);
            //MessageBox.Show(itemToReport.UserName);


        }

Upvotes: 1

Views: 1104

Answers (4)

Rohit Vats
Rohit Vats

Reputation: 81253

This will work for you -

MessageBox.Show(((sender as Button).DataContext as UserNames).UserName);

Upvotes: 0

Rachel
Rachel

Reputation: 132558

You can use the Button's DataContext, since it will be your UserName object

private void MyButton_Click(object sender, RoutedEventArgs e)
{
    Button b = sender as Button;
    UserNames data = b.DataContext as UserNames;

    MessageBox.Show(data.UserName);
}

I've always thought that with WPF, your application is the DataContext, while the UI objects like Buttons, ListBoxes, TextBoxes, etc are simply a pretty layer that sits on top of the DataContext to allow the User to interact with it.

Upvotes: 1

7heViking
7heViking

Reputation: 7577

To bind a datacollection it is often easiest to use an ObservableCollection (if the data is changing runtime). When you do the binding you have to define a datacontext, a datasoure and a datapath. I will advice you to read some more about binding on MSDN :D

Upvotes: 0

Wayne Tanner
Wayne Tanner

Reputation: 1356

In the XAML, set the Tag property to the current item.

In the click handler, cast it back.

Usernames user = (sender as Button).Tag as Usernames;

Upvotes: 1

Related Questions