我已将 Layer 的 ObservableCollection
绑定(bind)到 WPF 中的 TreeView
。
图层定义是:
public class Layer
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Color { get; set; }
public GeoType Type { get; set; }
}
public enum GeoType { Area, Line, Point }
这是 TreeView
XAML:
<TreeView Grid.Column="0"
ItemsSource="{Binding Layers}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding SubLayers}">
<StackPanel Orientation="Horizontal">
<Canvas Background="LightGray">
<Ellipse Fill="{Binding Color}"
Height="15"
Width="15"
StrokeThickness="5"
Stroke="{Binding Color}"/>
</Canvas>
<TextBlock Margin="20,0,0,0" Text="{Binding Path=Name}"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
我想根据 GeoType
属性指定形状类型。我的意思是,如果 GeoType
在上面的 XAML 中是 Line 而不是 canvas,那么它应该是 Line。
我如何使用绑定(bind)来做到这一点?我应该创建转换器吗?
最佳答案
您可以使用 和纯 XAML 来完成。
...
<Window.Resources>
<DataTemplate x:Key="LineTemplate">
<Line />
</DataTemplate>
<DataTemplate x:Key="EllipseTemplate">
<Ellipse />
</DataTemplate>
... etc
</Window.Resources>
...
<TreeView Grid.Column="0"
ItemsSource="{Binding Layers}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding SubLayers}">
<StackPanel Orientation="Horizontal">
<Canvas Background="LightGray">
<ContentControl Content="{Binding}">
<ContentControl.Style>
<Style TargetType="ContentControl">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Type}" Value="{StaticResource local:GeoType.Line}">
<Setter Property="ContentTemplate" Value="{StaticResource LineTemplate}" />
</DataTrigger>
<DataTrigger Binding="{Binding Path=Type}" Value="{StaticResource local:GeoType.Ellipse}">
<Setter Property="ContentTemplate" Value="{StaticResource EllipseTemplate}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</Canvas>
<TextBlock Margin="20,0,0,0" Text="{Binding Path=Name}"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
这只是众多可能解决方案中的一种。 local 是您的GeoType 所在的命名空间。您应该装饰资源内的模板以使用数据绑定(bind)。
关于c# - 形状类型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13890130/