如何为包含文本块的树视图设置IsSelected属性

时间:2019-06-26 11:51:06

标签: wpf treeview textblock selected

我创建了一个TreeView,并且TreeView的内部是一个Textblock:

 <TreeView x:Name="tvBelege" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="3" Grid.ColumnSpan="2" MinHeight="200" MaxHeight="300" Margin="5,5,5,5" SelectedItemChanged="TvBelege_SelectedItemChanged">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate DataType="local:Beleg" ItemsSource="{Binding Projektphasen}">
                <TextBlock Text="{Binding DisplayName}"/>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
 </TreeView>

加载对话框后,应自动选择一个项目,如下所示:

enter image description here

但是没有要设置的select或IsSelected这样的属性功能。我该怎么办?

1 个答案:

答案 0 :(得分:0)

向您的IsSelected类添加Beleg属性,并定义一个ItemContainerStyle,该属性将IsSelected容器的TreeViewItem属性绑定到它:

<TreeView x:Name="tvBelege" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="3" Grid.ColumnSpan="2" MinHeight="200" MaxHeight="300" Margin="5,5,5,5" SelectedItemChanged="TvBelege_SelectedItemChanged">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate DataType="local:Beleg" ItemsSource="{Binding Projektphasen}">
            <TextBlock Text="{Binding DisplayName}"/>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
    <TreeView.Resources>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
        </Style>
    </TreeView.Resources>
</TreeView>

然后,您设置要在视图模型中选择的Beleg对象的属性。