我正在使用WPF TreeView控件并面临奇怪的问题。 当我以编程方式添加TreeView项目时所有工作都正确,但是如果我通过绑定添加了项目 - 我的标题中有项目间隙:
此外,这个差距只是TreeItem行的一个“敏感”部分。我无法通过单击文本来选择项目,只有单击间隙区域才能选择它。 这是我的代码:
namespace WPFTreeViewExperience
{
/// <summary>
/// Data item interface
/// </summary>
public interface IMyTree
{
string Title { get; set; }
List<IMyTree> Items { get; set; }
}
/// <summary>
/// Hierarchical data model
/// </summary>
public class MyTreeLevel : IMyTree
{
public string Title { get; set; }
public List<IMyTree> Items { get; set; }
public MyTreeLevel(string Title, params MyTreeLevel[] Items)
{
this.Title = Title;
this.Items = new List<IMyTree>();
foreach (MyTreeLevel item in Items)
{
this.Items.Add(item);
}
}
}
/// <summary>
/// Viewmodel
/// </summary>
public class MyTreeViewModel : INotifyPropertyChanged
{
private void NotifyChanges(string PropName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropName));
}
}
private List<MyTreeLevel> _Tree;
public List<MyTreeLevel> MyTree
{
get
{
return _Tree;
}
set
{
_Tree = value;
NotifyChanges("MyTree");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public MyTreeViewModel()
{
List<MyTreeLevel> simpleTree = new List<MyTreeLevel>();
simpleTree.Add(new MyTreeLevel("1-0", new MyTreeLevel("1-1"),
new MyTreeLevel("1-2",
new MyTreeLevel("1-2-1"),
new MyTreeLevel("1-2-2")
),
new MyTreeLevel("1-3")));
simpleTree.Add(new MyTreeLevel("2-0", new MyTreeLevel("2-1"),
new MyTreeLevel("2-2",
new MyTreeLevel("2-2-1"),
new MyTreeLevel("2-2-2"),
new MyTreeLevel("2-3"))));
MyTree = simpleTree;
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
TreeExample.DataContext = new MyTreeViewModel();
}
}
}
和我的XAML代码:
<Window x:Class="WPFTreeViewExperience.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFTreeViewExperience"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TreeView Name="TreeExample" ItemsSource="{Binding MyTree}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Items}" DataType="{x:Type local:MyTreeLevel}">
<TreeViewItem Header="{Binding Title}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Window>
我的绑定有什么问题?
答案 0 :(得分:2)
我认为ItemTemplate应该是这样的:
<HierarchicalDataTemplate ItemsSource="{Binding Items}" DataType="{x:Type local:MyTreeLevel}">
<Grid>
<TextBlock Margin="0" Text="{Binding Path=Title}" />
</Grid>
</HierarchicalDataTemplate>