我正在使用DevExpress的WPF树列表视图,我发现了我认为与用作项目源的对象重命名属性相关的更普遍的问题.在树列表视图中,需要指定ParentFieldName和KeyFieldName(用于确定树的结构).这些字段是字符串.
这导致了重构代码的问题.例如,重命名我用作ItemSource的对象的属性将破坏树视图,因为ParentFieldName和KeyFieldName不再与属性名称同步.我通过在我的视图模型"ParentFieldName"和"KeyFieldName"中创建属性来解决这个问题,它使用nameof向视图显示属性名称.
这是控件的简化版本:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.DataContext>
<ViewModel />
</UserControl.DataContext>
<dxg:TreeListControl AutoGenerateColumns="AddNew"
EnableSmartColumnsGeneration="True" ItemsSource="{Binding Results}"
SelectionMode="Row">
<dxg:TreeListControl.View>
<dxg:TreeListView
ParentFieldName="{Binding ParentIdFieldName}" KeyFieldName="{Binding NodeIdFieldName}"
ShowHorizontalLines="False" ShowVerticalLines="False"
ShowNodeImages="True"/>
</dxg:TreeListControl.View>
</dxg:TreeListControl>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
和viewmodel:
using DevExpress.Mvvm;
public sealed class ViewModel : ViewModelBase
{
public string ParentIdFieldName => nameof(TreeNode.ParentId);
public string NodeIdFieldName => nameof(TreeNode.NodeId);
public ObservableCollection<TreeNode> Results
{
get => GetProperty(() => Results);
set => SetProperty(() => Results, value);
}
}
Run Code Online (Sandbox Code Playgroud)
和树节点:
public sealed class TreeNode
{
public int …Run Code Online (Sandbox Code Playgroud)