Harry Boy
Harry Boy

Reputation: 4777

XAML ListBox data binding - Add Click handler to each item

I wish to get all the files in a certain folder and display them in a ListView in WPF.

I have the following:

XAML

<ListBox Name="MyListBox"">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Code Behind

string location = AppDomain.CurrentDomain.BaseDirectory + "MyApp\\Documents\\";

string[] myFiles = Directory.GetFiles(location, "*.pdf")
                            .Select(path => Path.GetFileName(path).Replace(".pdf",""))
                            .ToArray();

MyListBox.ItemsSource = myFiles;

This lists all the files in a my list box.

What I wish to do is to add a CLick handler for each item in the list and call a function and pass in the text of the item clicked.

How can I do this?

Upvotes: 1

Views: 1625

Answers (2)

Stefan
Stefan

Reputation: 151

Just add the event in the ListBox:

<ListBox Name="MyListBox" MouseDoubleClick="Open_Click">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" >
                <TextBlock Text="{Binding}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

void Open_Click(object sender, EventArgs e) {
    ListBox listbox = sender as ListBox;
    string filename = listbox.SelectedItem.ToString();
}

Upvotes: 2

user1672994
user1672994

Reputation: 10849

If it's not a MVVM then you can define a button with handler which exist in code base. On each button click the same handler will be executed. Now question comes how to inject the file Name. So for that you can add the file Name in Tag object of button which can be read in code behind by handler for further processing.

XAML

<ListBox Name="MyListBox"">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding}" />
                <Button Click="Open_Click" Tag="{Binding}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Code Behind Handler

void Open_Click(object sender, EventArgs e)
{
   var button = sender as Button;
   var filename = Convert.ToString(button.Tag); // File Name
}

Upvotes: 4

Related Questions