开发者

Apply TreeView bindings to non-expanded notes

I want to use a hierarchical TreeView which I will populate programmatically.

My XAML file is as follows:

<Window.Resources>
    <HierarchicalDataTemplate 
        DataType="{x:Type local:MyTreeViewItem}" 
        ItemsSource="{Binding Path=Children}">
        <TextBlock Text="{Binding Path=Header}"/>
    </HierarchicalDataTemplate>
</Window.Resources>


<Grid>
    <TreeView Margin="12,12,422,33" Name="treeView1" SelectedItemChanged="treeView1_SelectedItemChanged" MouseDoubleClick="treeView1_MouseDoubleClick">
        <TreeView.ItemContainerStyle>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
                <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
            </Style>
        </TreeView.ItemContainerStyle>
    &开发者_Python百科lt;/TreeView>
</Grid>

The problem I'm having is that it seems that the bindings are applied only once the item is visible.

Suppose I populate the TreeView as follows:

private ObservableCollection<MyTreeViewItem> m_items;
private MyTreeViewItem m_item1;
private MyTreeViewItem m_item2;

public MainWindow()
{
    InitializeComponent();
    m_items = new ObservableCollection<MyTreeViewItem>();
    m_item1 = new MyTreeViewItem(null) {Header = "Item1"};
    m_item2 = new MyTreeViewItem(null) {Header = "Item2"};
    m_item1.Children.Add(m_item2);
    m_items.Add(m_item1);
    treeView1.ItemsSource = m_items;
}

I also have a button that selects m_item2:

private void button2_Click(object sender, RoutedEventArgs e)
{
    m_item2.IsSelected = true;
    m_item2.IsExpanded = true;
}

Now, if I launch the program and the TreeView only shows Item1 (Item2 is hidden because Item1 is not expanded), then clicking the button won't select m_item2. If I expand Item1 (thus making Item2 visible), the button will select m_item2.

Examining the PropertyChanged event on m_item2, I see that it is set to null initially, and a delegate is registered only once it is visible.

This is a problem for me because I want to be able to programmatically select an item, even if its parent has not yet been expanded (e.g. I want to be able to find a node in the tree).

I suppose I can programmatically expand and collapse all nodes, but it seems there should be a better way. Can someone suggest a solution?


Two suggestions:

1) Expand m_item1 before selecting m_item2

2) Hold your Selections in a ViewModel (using MVVM-Pattern)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜