Friday, August 29, 2008

Conditionally Setting Font Color In A WPF TreeView


I wanted to alert my users of validation errors for items in my TreeView by setting the font color to red and then changing the tooltip to display the error message. This is super easy to do with WPF by adding a couple of properties to the classes your TreeView displays. I changed my Info() property to conditionally return the normal tooltip or error message:

Public ReadOnly Property Info() As String

Get

Dim msg As String = ""

If ErrorMsg.Length = 0 Then

msg = ColumnList.Count & " column(s)"

Else

' Table is invalid

msg = ErrorMsg

End If

Return msg

End Get

End Property

Then I added a FontColor property that returns a Brush so the TextBlock.Foreground could bind to it:

Public ReadOnly Property FontColor() As Brush

Get

Dim c As Brush = Brushes.Black

If IsInvalid Then

c = Brushes.Red

End If

Return c

End Get

End Property

Then I change my XAML to bind to the new properties:

ToolTip="{Binding Path=Info}" Foreground="{Binding Path=FontColor}"


No comments: