【问题标题】:Access selected items of a ListBox that is within a DataTemplate访问 DataTemplate 中 ListBox 的选定项
【发布时间】:2017-05-30 05:53:18
【问题描述】:

我正在开发一个 UWP 应用,并且我的 XAML 中有一个动态 Pivot 控件。 在 Pivot 内部,使用 ListBox 填充 PivotItem。我希望能够检测到何时选择或取消选择 ListBox 项目。但似乎DataTemplate 中的任何控件都不能在代码隐藏文件中按名称引用。

所以,我不能做类似MyListBox.SelectedItems

这是我的 XAML:

        <Pivot.HeaderTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </Pivot.HeaderTemplate>

        <Pivot.ItemTemplate>
            <DataTemplate>
                <ListBox Name="MyListBox"
                         ItemsSource="{Binding List}"                            
                         SelectionMode="Multiple"
                         ScrollViewer.HorizontalScrollMode="Disabled"
                         HorizontalContentAlignment="Stretch"
                         SelectionChanged="FacetsListBox_SelectionChanged">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="9*"></ColumnDefinition>
                                    <ColumnDefinition Width="1*"></ColumnDefinition>                                       
                                </Grid.ColumnDefinitions>

                                <TextBlock Grid.Column="0"
                                           Text="{Binding read}"
                                           HorizontalAlignment="Left"
                                           VerticalAlignment="Center"/>

                                <TextBlock Text="{Binding num}"   
                                               Grid.Column="1"/>    
                            </Grid>                               
                        </DataTemplate>                            
                    </ListBox.ItemTemplate>
                </ListBox>
            </DataTemplate>
        </Pivot.ItemTemplate>

    </Pivot>

【问题讨论】:

  • 即使ListBox 在模板中,您仍然可以在代码中包含FacetsListBox_SelectionChanged 处理程序。
  • @JustinXL 我无法从代码隐藏中访问ListBox
  • 在该处理程序中,sender as ListBox 是您正在寻找的那个。 :)
  • 我可能需要一些额外的帮助。var MyListBox = sender as ListBox; var selected = MyListBox.SelectedItems as ObservableCollection&lt;IFacet&gt;; 给我 null
  • 你能告诉我你的代码背后的代码吗?

标签: xaml listbox uwp


【解决方案1】:

您可以使用 Behavior 并使用 AssociatedObject 来处理 ListBox 的事件,我认为这是解决问题的最简单方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多