【问题标题】:wpf access lisbox selected item if it isn't stringwpf 访问列表框选定的项目,如果它不强
【发布时间】:2011-10-19 05:31:17
【问题描述】:

我有一个列表框,它显示 Movie 对象数组中的 Name 属性

<ListBox Name="listBox1" SelectionChanged="listBox1_SelectionChanged">
                     <ItemsControl ItemsSource="{Binding}" >
                          <ItemsControl.ItemTemplate >
                              <DataTemplate >                                      
                                     <TextBlock Name="textBlock1" Text="{Binding Name}"/> 
                              </DataTemplate>
                          </ItemsControl.ItemTemplate>
                     </ItemsControl>
                 </ListBox>

如何在代码中访问 ListBox 内的 textBlock 的文本?
我必须在我的代码中使用 Name 属性的值

【问题讨论】:

    标签: wpf wpf-controls binding observablecollection


    【解决方案1】:

    当您执行上述操作时,itemscontrol 中的每个文本块都有一个名称 textblock1,其范围也仅限于每个项目容器。

    如果你想要单独的每个文本块,我通常会这样做:

    <TextBlock Text="{Binding Name}" Loaded="TextBlock_Loaded"/>
    

    并在代码中以您希望的任何方式注册这些文本框。可能是一个列表,

    List<TextBlock> TextBlockList = new List<TextBlock>();
    
    private void TextBlock_Loaded(object sender, RoutedEventArgs e)
            {
                TextBlockList.Add((TextBlock)sender);           
            }
    

    例如,访问这些东西:

    String FirstItem = TextBlockList.ElementAt(0).Text;
    

    【讨论】:

      【解决方案2】:

      列表框报告的选定项向您展示了拥有绑定在 TextBlock 中的 Name 属性的对象。至此游戏结束。

      【讨论】:

      • 我试过 Dim tempTB As TextBlock = CType(listBox1.SelectedItem, TextBlock) 但它不会从 ItemsControl 转换为 TextBlock
      • 没有。公开您在文本绑定中使用的“名称”属性的对象是什么? SelectedItem 属性给出了该对象。忘记文本块!
      • 我试过Dim tempMv As Movie = CType(listBox1.SelectedItem, Movie),但它给出了同样的错误。我有Me.listBox1.DataContext = Me.movieArraymovieArray = new ObservableCollection(of Movie)
      • 如果您通过代码设置DataContext,则在xaml中剪切ItemsSource上的{Binding}:不要同时使用。第一:你看到名单上的名字了吗?第二:在SelectionChanged事件处理器中,SelectedItem暴露的对象是什么?
      • 如果我删除 Itemssource 绑定,它不会显示任何内容,对象类型是 System.Windows.Controls.ItemsControl
      猜你喜欢
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多