Вы можете легко создавать данные времени проектирования:
Создайте свою модель данных:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class PersonCollection : List<Person>
{
public PersonCollection()
{
}
}
Создать файл с расширением .xaml
, содержащий:
DesignTimeTreeData.xaml
<local:PersonCollection xmlns:local="clr-namespace:Test_TreeWithDesignData">
<local:Person Name="Joan Solo" Age="32" />
<local:Person Name="Amara Skywalker" Age="31" />
</local:PersonCollection>
- Используйте
d:DataContext
и d:DesignData
для использования данных, которые вы указали в DesignTimeTreeData.xaml:
MainWindow.xaml
<Window x:Class="Test_TreeWithDesignData.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test_TreeWithDesignData"
Title="MainWindow"
Height="350"
Width="525"
mc:Ignorable="d">
<Grid>
<TreeView
d:DataContext="{d:DesignData Source=./DesignTimeTreeData.xaml}"
ItemsSource="{Binding}">
<TreeView.Resources>
<DataTemplate DataType="{x:Type local:Person}" >
<StackPanel Orientation="Horizontal" Height="25">
<Label Content="{Binding Name}"/>
<Label Content="{Binding Age}" Margin="3,0,0,0"/>
</StackPanel>
</DataTemplate>
</TreeView.Resources>
</TreeView>
</Grid>
</Window>
- Поскольку свойство
Window.DataContext
обычно установлено на ViewModel
, а TreeView.DataContext
является его коллекцией, для того, чтобы оба источника данных работали, вы можете окружить TreeView
Grid
, который DataContext
соответствует коллекции ViewModel
.
DummyViewModel.cs
public class DummyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public PersonCollection Persons { get; set; }
public DummyViewModel()
{
this.Persons = new PersonCollection();
}
}
MainWindow.xaml
<Window x:Class="Test_TreeWithDesignData.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test_TreeWithDesignData"
Title="MainWindow"
Height="350"
Width="525"
mc:Ignorable="d">
<Window.DataContext>
<local:DummyViewModel />
</Window.DataContext>
<Grid Name="RootGrid">
<Grid Name="TreeGrid" DataContext="{Binding Persons}">
<TreeView d:DataContext="{d:DesignData Source=./DesignTimeTreeData.xaml}"
ItemsSource="{Binding}">
<TreeView.Resources>
<DataTemplate DataType="{x:Type local:Person}" >
<StackPanel Orientation="Horizontal" Height="25">
<Label Content="{Binding Name}"/>
<Label Content="{Binding Age}" Margin="3,0,0,0"/>
</StackPanel>
</DataTemplate>
</TreeView.Resources>
</TreeView>
</Grid>
</Grid>
</Window>
Результат:
![enter image description here](https://i.stack.imgur.com/vKF4G.png)
Редактировать
Следующий вопрос будет следующим: как мне расширить элементы в конструкторе?
У Person
будет набор людей:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public PersonCollection Childs { get; set; }
}
Данные времени проектирования будут иметь ребенка
DesignTimeTreeData.xaml
<local:PersonCollection xmlns:local="clr-namespace:Test_TreeWithDesignData">
<local:Person Name="Joan Solo" Age="32" />
<local:Person Name="Amara Skywalker" Age="31">
<local:Person.Childs>
<local:PersonCollection>
<local:Person Name="Han Skywalker" Age="10" />
</local:PersonCollection>
</local:Person.Childs>
</local:Person>
</local:PersonCollection>
Теперь дерево будет иметь шаблон HierarchicalDataTemplate:
<HierarchicalDataTemplate
DataType="{x:Type local:Person}"
ItemsSource="{Binding Childs}">
<StackPanel Orientation="Horizontal" Height="25">
<Label Content="{Binding Name}"/>
<Label Content="{Binding Age}" Margin="3,0,0,0"/>
</StackPanel>
</HierarchicalDataTemplate>
И TreeView
свяжется с DesignerProperties.IsInDesignMode
, чтобы расширить элементы в конструкторе:
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<Style.Triggers>
<DataTrigger
Binding="{Binding RelativeSource={RelativeSource Self}, Path=(pf:DesignerProperties.IsInDesignMode)}"
Value="true"
>
<Setter Property="IsExpanded" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
Это xaml для окна:
MainWindow.xaml
<Window x:Class="Test_TreeWithDesignData.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test_TreeWithDesignData"
xmlns:pf="clr-namespace:System.ComponentModel;assembly=PresentationFramework"
Title="MainWindow"
Height="250"
Width="325"
mc:Ignorable="d"
>
<Window.DataContext>
<local:DummyViewModel />
</Window.DataContext>
<Grid Name="RootGrid">
<Grid Name="TreeGrid" DataContext="{Binding Persons}">
<TreeView
d:DataContext="{d:DesignData Source=./DesignTimeTreeData.xaml}"
ItemsSource="{Binding}"
>
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<Style.Triggers>
<DataTrigger
Binding="{Binding RelativeSource={RelativeSource Self}, Path=(pf:DesignerProperties.IsInDesignMode)}"
Value="true"
>
<Setter Property="IsExpanded" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.Resources>
<HierarchicalDataTemplate
DataType="{x:Type local:Person}"
ItemsSource="{Binding Childs}"
>
<StackPanel Orientation="Horizontal" Height="25">
<Label Content="{Binding Name}"/>
<Label Content="{Binding Age}" Margin="3,0,0,0"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
</Grid>
</Grid>
</Window>
И вот результат:
![enter image description here](https://i.stack.imgur.com/ehdE2.png)