从绑定列表框中获取选定的值

时间:2019-07-09 09:06:54

标签: c# wpf listbox tabcontrol

在TabControl内绑定ListBox可能有些困难。 TabControl也绑定到其中,而ListBox也绑定到其中。可以找到TabControl的标头值,但此后未检索到在ListBox中选择的值。

Main.xaml.cs

AddTab at = (AddTab)scenarioTC.SelectedItem;
MessageBox.Show(at.Header);
//listbox selecteditem show by Console or MessageBox

class AddTab
{
    public string Header { get; set; }
    public string Time { get; set; }
    public ObservableCollection<AddData> Data { get; } = new ObservableCollection<AddData>();
}

class AddData
{
    public string Name { get; set; }
    public string Path { get; set; }
}

Main.xaml

<TabControl x:Name="scenarioTC" ItemsSource="{Binding}" Grid.Row="1" HorizontalAlignment="Stretch" Margin="5,0,5,5"  VerticalAlignment="Stretch" SelectionChanged="ScenarioCB_SelectionChanged" KeyDown="ScenarioTC_KeyDown">
            <TabControl.ItemTemplate>
                <DataTemplate DataType="local:AddTab">
                    <TextBlock Text="{Binding Header}"/>
                </DataTemplate>
            </TabControl.ItemTemplate>
            <TabControl.ContentTemplate>
                <DataTemplate DataType="local:AddTab">
                    <ListBox x:Name="listBox" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch" ItemsSource="{Binding Data}" AllowDrop="True" Drop="ListBox_Drop" ScrollViewer.VerticalScrollBarVisibility="Disabled" ScrollViewer.HorizontalScrollBarVisibility="Visible" Padding="0">
                        <ListBox.ItemsPanel>
                            <ItemsPanelTemplate>
                                <WrapPanel IsItemsHost="True"/>
                            </ItemsPanelTemplate>
                        </ListBox.ItemsPanel>
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Vertical">
                                    <Image x:Name ="VD" Margin="3" Source="{Binding Path}" Height="180" Stretch="Uniform" HorizontalAlignment="Center"/>
                                    <TextBlock Name="TB" Margin="3" Text="{Binding Name}"/>
                                </StackPanel>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
                </DataTemplate>
            </TabControl.ContentTemplate>
        </TabControl>

1 个答案:

答案 0 :(得分:0)

方法1,尝试在AddTab中添加Listbox SelectedIndex属性,并在xaml DataTemplate中进行绑定。

方法2:

ListBoxItem listBoxItem= scenarioTC.ItemContainerGenerator.ContainerFromItem(scenarioTC.SelectedItem) as ListBoxItem;
Border border = VisualTreeHelper.GetChild(listBoxItem,0) as Border;
ListBox listBox = VisualTreeHelper.GetChild(border.Child,0);
var selectedItem = listbox.SelectedItem;

该代码未经测试,但可能有效。