【问题标题】:Use Style in TreeView HierarchicalDataTemplate在 TreeView HierarchicalDataTemplate 中使用样式
【发布时间】:2014-11-11 22:50:20
【问题描述】:

我是新手,无法退出获取正确的语法。这可以正确捕获树视图中文本框上的Left Mouse click

<HierarchicalDataTemplate 
                DataType="{x:Type r:NetworkViewModel}" 
                ItemsSource="{Binding Children}"
                >
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding NetworkIP}" Width="110" >
                             <TextBlock.InputBindings>
                                    <MouseBinding MouseAction="LeftClick"
                                    Command="{Binding DataContext.SelectItem, RelativeSource={RelativeSource FindAncestor, AncestorType=TreeView}}"
                                    CommandParameter="{Binding}" />
                             </TextBlock.InputBindings>
                        </TextBlock>

                    </StackPanel>
                </HierarchicalDataTemplate>

如何使用Resources 中的Style 块来完成此操作? 目标是对TreeView 中的所有TextBoxes 使用相同的样式。可以放在Usercontrol.Resources 中并被HierarchicalDataTemplate 引用的东西。

【问题讨论】:

    标签: c# wpf xaml treeview


    【解决方案1】:

    如果我理解正确,您可以在控件或 Windows 资源中定义一个具有目标类型(与键 x:Key=... 相对)的模板,以使其自动应用于树视图中的所有项目。

    这是一个小例子,在窗口资源中定义了一个模板,其中包含InputBindings 定义。如果ItemsControlTreeView 没有明确定义其他模板,则此模板将自动应用于ItemViewModel 类型的所有对象。在此示例中,项目以简单的 ItemsControl 显示,但它同样适用于 TreeView

    请注意,要使其正常工作,TreeView 中的所有项目都必须属于同一类型。 如果它们派生自相同的基本类型是不够的。仅当Template.DataType 中定义的类型与 ViewModel 的类型完全相同时,才会应用模板。如果您的 TreeViews ItemsScources 包含混合类型,则需要分别为每种类型指定模板。

    <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">
    
        <Window.Resources>
            <DataTemplate DataType="{x:Type loc:ItemViewModel}">
                <TextBlock Text="{Binding Name}" Width="110" >
                    <TextBlock.InputBindings>
                        <MouseBinding 
                            MouseAction="LeftClick"
                            Command="{Binding SelectItem}" />
                    </TextBlock.InputBindings>
                </TextBlock>
            </DataTemplate>
        </Window.Resources>
    
        <Grid>
            <ItemsControl ItemsSource="{Binding Items}" />
        </Grid>
    </Window>
    

    【讨论】:

    • 谢谢!太糟糕了,我不能在 XAML 中使用基本类型或接口,这样会更简单。再次感谢所有伟大的帮助!
    • 不客气!也许您可以考虑为几种模型类型使用一种 ViewModel 类型,这些模型类型都派生自一个基类。视情况而定,但也许值得考虑。干杯,祝你好运!
    猜你喜欢
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多