2010-02-19 78 views
1

推倒前臺我在做:WPF結合與GridViewColumn

<ListView Margin="34,42,42,25" Name="listView1"> 
    <ListView.View> 
    <GridView> 
     <GridViewColumn Width="550" Header="Value" DisplayMemberBinding="{Binding Path=MyValue}"/> 
    </GridView> 
    </ListView.View> 
    <ListView.Resources> 
    <Style TargetType="{x:Type TextBlock}"> 
     <Setter Property="Foreground" Value="Green"/> 
    </Style> 
    </ListView.Resources> 
</ListView> 

,這是工作,我可以看到我的綠色項目。

現在,我想用這種具有約束力的價值,所以我有一個屬性:

private Color _theColor; 

public System.Windows.Media.Color TheColor 
{ 
    get { return _theColor; } 
    set 
    { 
     if (_theColor != value) 
     { 
      _theColor = value; 
      OnPropertyChanged("TheColor"); 
     } 
    } 
} 

,但如果我用這個綁定:

<Setter Property="Foreground" Value="{Binding Path=TheColor}"/> 

它不工作...

我該如何糾正?

當然,我的TheColor設置爲Colors.Green ...

感謝您的幫助

回答

1

容易,你不能綁定到一個ColorForeground需要設置爲Brush。所以我的值設置爲SolidColorBrushBrush的顏色屬性綁定到你的TheColorDependencyProperty

<Style TargetType="{x:Type TextBlock}"> 
    <Setter Property="Foreground"> 
     <Setter.Value> 
      <SolidColorBrush Color="{Binding Path=TheColor}" /> 
     </Setter.Value> 
    </Setter> 
</Style> 

在我的例子中,我只是綁定的屬性TheColorDependencyProperty

public static readonly DependencyProperty TheColorProperty = 
DependencyProperty.Register("TheColor", typeof(System.Windows.Media.Color), typeof(YourWindow)); 

public System.Windows.Media.Color TheColor 
{ 
    get { return (System.Windows.Media.Color)GetValue(TheColorProperty); } 
    set { SetValue(TheColorProperty, value); } 
} 

後那你可以綁定到TheColorDependencyProperty。在我的情況下,我只是給主窗口/用戶控制/頁面一個x:名稱並綁定到:

<SolidColorBrush Color="{Binding Path=TheColor, ElementName=yourWindowVar}" /> 
+0

感謝它的工作 – Tim 2010-02-19 16:08:15