开发者

Wpf binding to Foreground with GridViewColumn

I'm doing :

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

and this is working, I can see my items in Green.

Now, I want to use a binding value with this, so I have a property :

private Color _theColor;

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

but If I use this binding :

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

It's not working...

How can I correct that ?

Of course, I'm setting the TheColor to Colors.Green ...

Thanks for your help


Easy, you can't bind to a Color. The Foreground need to be set to a Brush. So I would set the value to a SolidColorBrush and bind the Brush's color property to your TheColor DependencyProperty:

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

In my example I just bound the property TheColor to a 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); }
}

After that, you can bind to the TheColor DependencyProperty. In my case, I just gave the main Window/UserControl/Page an x:Name and bound to that:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜