![](/img/trans.png)
[英]TreeViewItem with ItemsSource Right-Click doesn't select the Item
[英]TreeViewItem template click/select/highlight issue
我是 WinUI 3 的新手,目前正在构建一个 TreeView (CommunityToolkit),我可以在其中拖放 TreeViewItems。 我拥有的 TreeViewItem 由 3 个部分组成,一个组名称、一个显示名称和子项目。 代码的拖放部分工作正常,但是存在一个问题,即单击某个项目并不总是选择/突出显示它,而且我似乎无法找到关于原因的根本问题。 见下图。
在上图中,第一个项目被“选中”,因为我希望它在左侧有蓝色突出显示。 但是当我点击其他 2 个项目(1 级或 2 级)中的任何一个时,我观察到以下行为。
见下方XAML
<Grid>
<Border BorderThickness="2" BorderBrush="DimGray">
<TreeView AllowDrop = "True"
CanDragItems="True"
CanReorderItems = "False"
ItemsSource="{x:Bind Items}"
SelectedItem="{x:Bind SelectedDemoItem, Mode=TwoWay}">
<TreeView.ItemTemplate>
<DataTemplate x:DataType="local:DemoItem">
<TreeViewItem AllowDrop="True"
CanDrag="True"
CollapsedGlyph=""
ExpandedGlyph=""
IsExpanded="True"
ItemsSource="{x:Bind Children}"
Padding="-10,0,0,0">
<TreeViewItem.Content>
<StackPanel AllowDrop="True"
BorderBrush="Red"
BorderThickness="1"
CanDrag="True"
Orientation="Horizontal">
<TextBlock FontSize="14"
FontWeight="ExtraBold"
IsColorFontEnabled="True"
Margin="0,0,10,0"
MinWidth="30"
TextAlignment="Center"
Text="{x:Bind Group}" />
<TextBlock Text="{x:Bind DisplayName}" Margin="0,0,5,0"/>
</StackPanel>
</TreeViewItem.Content>
</TreeViewItem>
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Border>
</Grid>
和代码隐藏
public sealed partial class TestUserControl : UserControl
{
public TestUserControl()
{
InitializeComponent();
FillData();
}
private void FillData()
{
var level0 = new DemoItem { DisplayName = "Level 0", Group = Groups.M };
var level1 = new DemoItem { DisplayName = "Level 1", Group = Groups.U };
var level2 = new DemoItem { DisplayName = "Level 2", Group = Groups.C };
level1.Children.Add(level2);
level0.Children.Add(level1);
Items.Add(level0);
Items.Add(level0);
}
public ObservableCollection<DemoItem> Items { get; } = new();
public DemoItem SelectedDemoItem { get; set; }
}
public enum Groups
{
S, M, U, C
}
public class DemoItem
{
public string DisplayName { get; set; }
public ObservableCollection<DemoItem> Children { get; } = new();
public Groups Group { get; set; }
}
出于此测试的目的,我删除了所有拖放代码,因为它们对上述问题没有影响。 但是,我发现只有在我的项目模板中将 CanDrag 设置为 True 时才会出现此问题,这可能会有所帮助。
解决此问题的任何帮助将不胜感激。
由于TextBlocks
,点击事件不会到达TreeViewItem
。 最简单的方法是在两个TextBlocks
上禁用IsHistTestVisible
。
<TextBlock
MinWidth="30"
Margin="0,0,10,0"
FontSize="14"
FontWeight="ExtraBold"
IsColorFontEnabled="True"
IsHitTestVisible="False"
Text="{x:Bind Group}"
TextAlignment="Center" />
<TextBlock
Margin="0,0,5,0"
IsHitTestVisible="False"
Text="{x:Bind DisplayName}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.