首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

[]wpf中TreeView的显示有关问题

2013-08-04 
[求助]wpf中TreeView的显示问题想做一个基于WPF的目录树具体的效果是这样的每个TreeViewItem显示文件夹分

[求助]wpf中TreeView的显示问题
想做一个基于WPF的目录树
具体的效果是这样的
[]wpf中TreeView的显示有关问题
每个TreeViewItem显示文件夹
分别显示图标、文件夹名称和当前文件夹的子文件夹个数

现在问题就是第三项显示“当前文件夹的子文件夹个数”这一项总是为0。(调试有数值,但界面显示0)
前台代码

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:loc="clr-namespace:WpfApplication2"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TreeView>
            <loc:MyTreeViewItem x:Name="MyFiles">
                <loc:MyTreeViewItem.Header>
                    <StackPanel Orientation="Horizontal">
                        <Image Width="16" Height="16" Source="/WpfApplication2;component/Images/Folder.png" />
                        <TextBlock Text="我的文件"></TextBlock>
                        <TextBlock Text="{Binding Count}" Margin="5,0,0,0"></TextBlock>
                    </StackPanel>
                </loc:MyTreeViewItem.Header>
                <loc:MyTreeViewItem>
                    <loc:MyTreeViewItem.Header>
                        <StackPanel Orientation="Horizontal">
                            <Image Width="16" Height="16" Source="/WpfApplication2;component/Images/Folder.png" />


                            <TextBlock Text="我的文件的文件"></TextBlock>
                            <TextBlock Text="{Binding Count}" Margin="5,0,0,0"></TextBlock>
                        </StackPanel>
                    </loc:MyTreeViewItem.Header>
                </loc:MyTreeViewItem>
            </loc:MyTreeViewItem>
        </TreeView>
    </Grid>
</Window>



后台TreeViewItem.cs代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;

namespace WpfApplication2
{
    class MyTreeViewItem:TreeViewItem
    {
        public int Count
        {
            get 
            {
                return this.Items.Count;
            }
        }

        public MyTreeViewItem()
        {
            this.DataContext = this;
        }
    }
}


由于Count属性是只读的,因此INotifyPropertyChanged接口也用不上了。
求cdsn的大牛指导。

另外我将TreeViewItem封装成UserControl再添加到的话,在TreeView中就没法选中封装好的UserControl(也就是没法选中然后背景变蓝),求大牛指导指导。


[解决办法]
INotifyPropertyChanged接口不一定要用在对应的属性上面,只要在合适的时候触发它即可。
例如:


        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

上面的是基本定义,然后你在添加子项时调用OnPropertyChanged("Count")方法即可,如果你可以确定是哪个方法添加的子项,并且那个方法能被override,那么直接在该方法内调用OnPropertyChanged("Count")方法即可,那样就不需要设置为public了。

热点排行