如何获取列表框的选定项绑定元素?

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

所以这是我的问题: 我希望从列表框中的选定元素中找到名为 "id" 的绑定字符串。 这是我的 .xaml:

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

我的 c# 发送数据以填充列表框:

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()});                                   
}

我尝试了各种不同的方案,但还没有任何效果:/

试试下面的代码

    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;
    }

我假设您没有使用 MVVM。

您可以在代码中添加以下依赖项 属性 及其包装器:

    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));

在您的列表框中只需添加

SelectedItem="{Binding SelectedArticle}"

每次更改选择时,SelectedArticle 都会收到通知,您将能够轻松访问您的属性。

但请尝试使用数据绑定到 ObservableCollection,而不是使用 foreach 遍历您的集合。

实际上我找到了一种更简单的方法来完成这项工作(无论如何感谢您的帮助):

Article selectedArticle = lstView.SelectedItem as Article;

然后要获取绑定到该元素的任何字符串,请调用:

selectedArticle.nameofthebindedstring