我在SL4中有一个已经填充的TreeView,并且选择了某个TreeViewItem。
刚做
treeview.Visibility=Visibility.Collapsed;
然后
treeview.Visibility=Visibility.Visible;
修改选择的TreeViewItem。为什么?有没有办法避免这种情况?
编辑2012.02.04 03:29
我已将问题追溯到根本。这是我发现的(对我而言,令人惊讶的)结论:如果满足以下所有条件:
1)TreeView有两个(或更多)深度级别,
2)我首先扩展其所有节点,
3)我开始在第二级选择一个节点,
4)(这是最奇怪的一个)我用来折叠的按钮再次显示TreeView不是制表位,
然后TreeView在折叠后不再保留其选择并再次显示!!!
请下载从中重现问题的小型解决方案+示例 http://src041.bluemosfet.net/treeviewselectsanotheritem.zip 并尝试一下。
或者看看这两段代码:
<UserControl x:Class="PRJ.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" Loaded="UserControl_Loaded">
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel Name="sp1">
<!-- ################################################################### -->
<!-- First, in the TreeView, expand TreeViewItems "a0", "a1" and "a2". -->
<!-- Then, select "a0b0". -->
<!-- Then, click the button twice. -->
<!-- If you don't remove IsTabStop="False" from the following line of code, the TreeView reappears with "a1" selected !!! -->
<!-- If you continue clicking the button, the selection shifts to "a1b0", "a2", and finally "a2b0". -->
<!-- If you remove IsTabStop="False" , or change it to True, the TreeView works OK and keeps its selection. -->
<!-- Isn't it odd, that the capability of the TreeView to keep its selection depends on whether the button used to hide and show the TreeView is a tab stop or not??? -->
<Button Content="Hide/Show TreeView" Name="b1" Click="b1_Click" IsTabStop="False" />
<!-- ################################################################### -->
<sdk:TreeView Name="tv1" />
</StackPanel>
</Grid>
</UserControl>
和
namespace PRJ
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void b1_Click(object sender, RoutedEventArgs e)
{
if (tv1.Visibility==Visibility.Collapsed)
tv1.Visibility=Visibility.Visible;
else
tv1.Visibility=Visibility.Collapsed;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
for (int a=0;a<3;a++)
{
TreeViewItem tvia =new TreeViewItem();
tvia.Header =String.Format("a{0}",a);
for (int b=0;b<2;b++)
{
TreeViewItem tvib =new TreeViewItem();
tvib.Header =String.Format("a{0}b{1}",a,b);
tvia.Items.Add(tvib);
} // for b
tv1.Items.Add(tvia);
} // for a
}
}
}
TreeView保持其选择的能力是否很奇怪取决于用于隐藏和显示TreeView的按钮是否是制表位?
答案 0 :(得分:0)
用一个全新的项目和一个用字符串列表提供的树视图进行测试。折叠后再也不会丢失所选项目。