简体   繁体   中英

How can I display data of the ListBox item in the dialog?

In my WPF program I have ListBox control:

<ListBox x:Name="mailsListBox" SelectionChanged="mailsListBox_SelectionChanged" >
    <ListBoxItem Content="..." Background="#FFF3F3F3" Margin="0,0,0,1" />
    <ListBoxItem Content="..." Margin="0,0,0,1"/>
    <!-- ... -->
    <ListBoxItem Content="..." Background="#FFF3F3F3" Margin="0,0,0,1" />
    <ListBoxItem Content="..." Margin="0,0,0,1"/>
</ListBox>

When I press on it's component, I need to show a dialog window, but here what I have:

在此处输入图片说明

Displays the corresponding value:

public class Emails
{
    public Emails()
    {
        AddMailsToList();
    }

    public List<string> mailsList = new List<string>();

    public void AddMailsToList()
    {
        MainWindow obj = new MainWindow();
        mailsList.Add(obj.mailsListBox.Items[0].ToString());
        mailsList.Add(obj.mailsListBox.Items[1].ToString());
        //...
        mailsList.Add(obj.mailsListBox.Items[9].ToString());

        // title of the mail
        mailsList.Add("You have new message");
    }
}

Interception click event to an element ListBox:

public partial class MainWindow : MetroWindow
{
    private async void mailsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        Emails obj = new Emails();

        await this.ShowMessageAsync(
            obj.mailsList[10],
            obj.mailsList[mailsListBox.SelectedIndex]);
    }
}

How can I display only data which I need in the dialog?

Edit1:

I thins I have a wrong code structure and I need to use ItemsSource , but I don't know how to..

I don't understand the point of the Email class, and I think you definitely have a data model structure problem.

But if you just want to display the text of the selected item of your listbox, give a try to that :

    private void mailsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ListBox lb = (ListBox)sender;
        if (lb != null && !string.IsNullOrEmpty(lb.SelectedItem.ToString()))
        {
            await this.ShowMessageAsync(
        ((ListBoxItem)lb.SelectedItem).Content.ToString(),
        obj.mailsList[mailsListBox.SelectedIndex]);
        }
    }

Always check if user has selected an item. if you use mailsListBox.SelectedIndex and user hasn't select anything, it will return -1, and it will throw an error when you try to access to item at position "-1" of an array :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM