Wpf 如何通过编程将按钮添加到单个TreeView项目
我动态生成TreeView(TV)的内容,并根据我用于生成树的项目的某些属性,希望将按钮附加到某些TreeView(TV)项目 碰巧我的应用程序中一台特定电视的所有电视都需要此功能。可以简化任务的是,该树中的所有根项都需要按钮。换言之,特定电视内的每个TVI都需要一个按钮,但电视内的TVI除外 我在想模板的想法,但我只能看到如何添加按钮,以所有的电视在电视上。另一种选择(我想……我还没有尝试过,但在我的脑海里听起来还可以)是只在电视中的所有东西上添加按钮,并将源项目的相关属性绑定到按钮的可视性上,但这似乎是一种完全的破解,我相信必须有一个更优雅的解决方案Wpf 如何通过编程将按钮添加到单个TreeView项目,wpf,button,treeviewitem,Wpf,Button,Treeviewitem,我动态生成TreeView(TV)的内容,并根据我用于生成树的项目的某些属性,希望将按钮附加到某些TreeView(TV)项目 碰巧我的应用程序中一台特定电视的所有电视都需要此功能。可以简化任务的是,该树中的所有根项都需要按钮。换言之,特定电视内的每个TVI都需要一个按钮,但电视内的TVI除外 我在想模板的想法,但我只能看到如何添加按钮,以所有的电视在电视上。另一种选择(我想……我还没有尝试过,但在我的脑海里听起来还可以)是只在电视中的所有东西上添加按钮,并将源项目的相关属性绑定到按钮的可视性上
关于如何实现这一点,您有什么想法吗?如果您是根据视图模型中的属性动态构建数据,那么您可以考虑使用 在实现中,检查数据项是否有子项。如果是,则返回带有按钮的数据模板。如果没有,则返回不带按钮的数据模板。比如:
public class ButtonDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item,
DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
if (element != null)
{
YourClass itemAsYourClass = item as YourClass;
if(itemAsYourClass != null)
{
bool hasChildren = itemAsYourClass.Children != null
&& itemAsYourClass.Children.Count > 0;
return element.FindResource(hasChildren
? "withButtonTemplate"
: "withoutButtonTemplate"
);
}
}
return null;
}
}
以下是我使用的代码: 类CurrentDriveDataTemplateSelector:DataTemplateSelector { 公共数据模板currentDriveTemplate{get;set;} 公共数据模板dirTemplate{get;set;}
public override DataTemplate SelectTemplate(object item,
DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
if (element != null)
{
Directory dir = item as Directory;
if (dir != null)
{
bool isCurrentDrive = ((dir.parent == 0) && (dir.state == "current"));
if (isCurrentDrive)
{
return currentDriveTemplate;
}
return dirTemplate;
}
}
}
}
<HierarchicalDataTemplate x:Key="normalDirTemplate" ItemsSource="{Binding Path=childdirs}">
<TextBlock Text="{Binding Path=name}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate x:Key="currentDriveTemplate" ItemsSource="{Binding Path=childdirs}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=name}" Width="100"/>
<Button Content="=>" Width="20"></Button>
</StackPanel>
</HierarchicalDataTemplate>
<mine:CurrentDriveDataTemplateSelector
currentDriveTemplate="{StaticResource currentDriveTemplate}"
dirTemplate="{StaticResource normalDirTemplate}"
x:Key="CurrentDriveDataTemplateSelector"/>
...blah
<TreeView Height="324" Margin="0,25,0,0" x:FieldModifier="private" x:Name="currentDirectoryTree" Width="150" ItemTemplateSelector="{StaticResource CurrentDriveDataTemplateSelector}">
...etc
public override DataTemplate SelectTemplate(对象项,
DependencyObject(对象容器)
{
FrameworkElement=容器作为FrameworkElement;
if(元素!=null)
{
Directory dir=项目作为目录;
if(dir!=null)
{
bool isCurrentDrive=((dir.parent==0)和&(dir.state==current”);
如果(isCurrentDrive)
{
返回当前驱动模板;
}
返回目录模板;
}
}
}
}
……废话
等
您尝试了什么。你应该能够在树视图中循环浏览这些项目,我相信有一种方法可以确定哪些项目是根,哪些是子项。谢谢,救了我的命。我将我的代码放在下面,以供那些渴望了解如何实现这一目标的所有细节的人使用