2013-04-24 80 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> 

,我成功地獲得財產。