简体   繁体   中英

How can I get a listbox's selected item binded element?

So here is my problem: I am looking to find the binded string named "id" from the selected element in my listbox. Here is my .xaml:

<ListBox Name="lstView">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid/>                                   
                <TextBlock Text="{Binding id}"/>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

And my c# which sends data to fill the listbox:

var articles = root.data.movies.Select(m => new Article { Name = m.title, ImagePath = m.medium_cover_image, Year = m.year.ToString() }).ToList();
foreach (Article s in articles)
{
    this.lstView.Items.Add(new Article {id = m.id.ToString()});                                   
}

I have tried various different scenarios, but nothing has worked yet :/

Try the below code

    if(lstView.SelectedItems.Count=0)
    {
      return;
    }
    var selectedItem=lstView.SelectedItem[0] as FrameWorkElement;
    var itemDataContext=selectedItem.DataContext as Article;
    if(itemDataContext!=null)
    {
        //do what you like with the object
        string idString=itemDataContext.id;
    }

I assume you are not using MVVM.

You can add to your code behind the following Dependency Property and its wrapper:

    public Article SelectedArticle
    {
        get { return (Article)GetValue(SelectedArticleProperty); }
        set { SetValue(SelectedArticleProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SelectedArticle.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SelectedArticleProperty =
        DependencyProperty.Register("SelectedArticle", typeof(Article), typeof(MainWindow), new PropertyMetadata(null));

On your ListBox just add

SelectedItem="{Binding SelectedArticle}"

and every time you change the selection, SelectedArticle will be notified and you will be able to easily access your properties.

But try to use data binding to an ObservableCollection instead of iterating over your collection with foreach.

Actually I found a way simpler way to get this working (thanks for your help anyway):

Article selectedArticle = lstView.SelectedItem as Article;

And then to get any string binded to that element you call:

selectedArticle.nameofthebindedstring            

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