2012-12-15 31 views
2

我已将Layer的ObservableCollection绑定到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是Line而不是在上面的XAML画布,它应该是Line。 我怎样才能使用绑定?我应该创建转换器吗?

回答

1

你可以用纯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> 

它只是许多可能solutuion之一。 本地是您的GeoType所在的命名空间。您应该在资源内部修饰模板以使用数据绑定。

+0

谢谢。这非常有帮助。我怎样才能绑定颜色属性的形状的颜色? – Shahin

+0

谢谢。这是非常有帮助的,正如你所说的“你应该在资源内部修饰模板以使用数据绑定” 这是正确的: <合同:GeoType x:Key =“local:GeoType.Line”/> <合同:GeoType x :Key =“local:GeoType.Area”/> <合同:GeoType x:Key =“local:GeoType.Point”/> -------- Shahin

+1

就像你之前做的一样 - 资源DataTemplates。你的DataContext将是Layer类型的,你可以使用[这个答案](http://stackoverflow.com/questions/672991/how-do-i-convert-a-string-like-red-to-a-system -windows-media-color)来获取真正的颜色,而不是字符串。 – stukselbax