Wpf使用GridViewColumn绑定到Foreground

时间:2010-02-19 12:51:06

标签: wpf data-binding listview 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 个答案:

答案 0 :(得分:1)

很简单,您无法绑定ColorForeground需要设置为Brush。所以我会将值设置为SolidColorBrush并将Brush的颜色属性绑定到TheColor DependencyProperty

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

在我的示例中,我将属性TheColor绑定到DependencyProperty

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); }
}

之后,您可以绑定到TheColor DependencyProperty。在我的例子中,我只给了主窗口/用户控件/页面一个x:名称并绑定到:

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