2013-04-24 83 views
0

我使用下面的代码 -不能设置颜色越来越由视图模型

<Label Grid.Row="0" Content="{Binding MyColor}"> 
    <Label.Background> 
    <SolidColorBrush Color="{Binding MyColor}"></SolidColorBrush> 
    </Label.Background> 
</Label> 

<Grid Grid.Row="1" Grid.Column="0"> 
    <ScrollViewer Name="MyScroll" 
       Template="{DynamicResource MyScrollViewerControlTemplate}"> 
    <ListView Name="List1" 
       BorderThickness="0" 
       SelectedItem="{Binding Path=SelectedElement}" 
       ItemsSource="{Binding Path=Elements}" 
       Background="{StaticResource aColor}"> 

     <ListView.Resources> 
     <ControlTemplate x:Key="SelectedTemplate" 
         TargetType="ListViewItem"> 
      <Border Cursor="Hand"> 
      <Border.Background> 
       <SolidColorBrush Color="{Binding Path=myColor}"> 
       </SolidColorBrush> 
      </Border.Background> 
      <TextBlock Text="Test" /> 
      </Border> 
     </ControlTemplate> 
     </ListView.Resources> 
    </ListView> 
    </ScrollViewer> 
</Grid> 

这里的时候,我使用属性myColor来设置标签背景颜色,它工作正常,但是当我做在同ListView它不工作。

我错过了什么。请建议。

回答

0

我找到了答案。我在ListView中将Elements引用为我的绑定源,它不具有直接访问myColor属性的权限。我需要在可视化树中搜索DataContext并需要引用它。

我用下面的代码 -

<Border.Background> 
    <SolidColorBrush 
    Color="{Binding Path=DataContext.myColor, RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Grid}}}"> 
    </SolidColorBrush> 
</Border.Background> 

,我成功地获得财产。