我在一个窗口中有一个TreeView,它作为对话框打开。单击某个项目时,将选中该项目。但是当有服务调用时,所选项目将更改为根项目。 TreeView的DataContext是一个“authors”数组,每个都包含一个“books”数组,其中包含一个“pages”数组。我从服务调用获取“作者”数组以及“页面”PDF的字节。 “作者”和“书籍”显示在TreeView中,但“页面”不显示。单击“书籍”时,“页面”数组将加载到组合框中,第一个“页面”将显示在PDF查看器中。通过服务调用从服务器加载“页面”。仅当我使用服务调用时,才会选择TreeView中的根“author”项。
注意:这是我实际使用的代码,但由于我公司的隐私政策,事情名称已更改。但功能和结构上的一切都是一样的。
这基本上是XAML和背后的代码。
XAML:
<Window.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:author}" ItemsSource="{Binding Path=books}">
<TextBlock Text="{Binding name}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:book}" >
<TextBlock Text="{Binding title}"/>
</HierarchicalDataTemplate>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" MinWidth="125"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<GridSplitter HorizontalAlignment="Right" VerticalAlignment="Stretch" Grid.Column="1" Grid.RowSpan="2" ResizeBehavior="PreviousAndNext" Width="5" Background="#FFBCBCBC"/>
<TreeView x:Name="booksTreeView" Grid.Column="0" Grid.RowSpan="2" SelectedItemChanged="booksTreeView_SelectedItemChanged" Background="WhiteSmoke"/>
<ComboBox x:Name="pagesDropBox" Grid.Column="2" Grid.Row="0" HorizontalAlignment="Left" MinWidth="100" SelectionChanged="pagesDropBox_SelectionChanged" />
<Grid Grid.Column="2" Grid.Row="1" x:Name="previewHolderGrid"/>
</Grid>
C#:
private void booksTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
TreeView tree = sender as TreeView;
book b = tree.SelectedItem as book;
if (b != null)
{
e.Handled = true;
pagesDropBox.ItemsSource = db.pages;
if (b.pages.Count > 0)
pagesDropBox.SelectedIndex = 0;
}
}
private void pagesDropBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
previewHolderGrid.Children.Clear();
Guid p = pagesDropBox.SelectedItem as Guid;
if (p != Guid.Empty)
{
byte[] bytes = ServiceAccess.Instance.GetPage(p); //This is the line that will cause the root item to be selected even if the next line is commented out
this.previewHolderGrid.Children.Add(new PDFViewer.PdfViewerControl(bytes));
}
}
Datacontext对象:
public class author{
String name;
BindingList<book> books;
}
public class book{
String title;
BindingList<Guid> pages;
}