WPF MVVM - TreeView中的项目的样式丢失

时间:2015-07-22 20:07:34

标签: wpf xaml mvvm treeview styles

我刚开始使用WPF,而且我遇到了样式问题。 我有一种风格用于TextBlock中的所有UserControl

<UserControl.Resources>
    <Style TargetType="TextBlock">
        <Setter Property="Margin" Value="10" />
    </Style>
</UserControl.Resources>

它适用于第一个TextBlock中的StackPanel,但不适用于TextBlock中的TreeView

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition />
    </Grid.RowDefinitions>

    <StackPanel Grid.Row="1" Orientation="Horizontal">
        <TextBlock Text="{Binding Name}" />
        <TextBlock Text="{Binding Description}" />
    </StackPanel>

    <TreeView ItemsSource="{Binding Tests}" Grid.Row="2">
        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type dml:TestCase}" ItemsSource="{Binding Tasks}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" />
                    <TextBlock Text="{Binding Description}" />
                </StackPanel>
            </HierarchicalDataTemplate>

            <!--Task Template-->
            <HierarchicalDataTemplate DataType="{x:Type dml:Task}">
                <TextBlock Text="{Binding Name}" />
            </HierarchicalDataTemplate>
        </TreeView.Resources>
    </TreeView>
</Grid>

如果没有为TextBlock中的每个TreeView设置样式,有没有办法呢?

2 个答案:

答案 0 :(得分:1)

只需在你的ItemTemplate中执行:

<HierarchicalDataTemplate>
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}" Margin="0,0,10,0" />
        <TextBlock Text="{Binding Description}" />
    </StackPanel>
</HierarchicalDataTemplate>

答案 1 :(得分:1)

好的,我们走了,

<TreeView ItemsSource="{Binding Tests}" >
        <TreeView.Resources>
            <HierarchicalDataTemplate ItemsSource="{Binding Tasks}" DataType="Hdtable1">
                <StackPanel Orientation="Horizontal">
                    <StackPanel.Resources>
                        <Style TargetType="{x:Type TextBlock}">
                            <Setter Property="Margin" Value="10"/>
                        </Style>
                    </StackPanel.Resources>
                    <TextBlock Text="{Binding Name}" />
                    <TextBlock Text="{Binding Description}" />
                </StackPanel>
            </HierarchicalDataTemplate>
            <HierarchicalDataTemplate DataType="HDTEmplate">
                <TextBlock Text="{Binding Name}" />
            </HierarchicalDataTemplate>
        </TreeView.Resources>
    </TreeView>

致谢: - https://stackoverflow.com/a/932609/2470362
https://stackoverflow.com/a/3102188/2470362