Click here to Skip to main content
15,790,957 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear community,

in my WPF project I encountered a strange behavior: I want to update the content of a label by a DataTrigger if an Integer value reaches 0 (zero). Unfortunately that doesn´t work but for String values (= text, not numbers as text) it works. Even if I convert the Integer to String via .ToString() or CType() it doesn´t work. To recheck that I created a new WPF project but here I have the same problem. The Debugger doesn´t report an error.

My XAML of the new project:

<Window x:Class="MainWindow"
    Title="MainWindow" Height="350" Width="525">
        <Label Name="lbl">
                <Style TargetType="Label">
                    <Setter Property="Content" Value="Ready" />
                        <DataTrigger Binding="{Binding ElementName=lbl, Path=Content}" Value="0">
                            <Setter Property="Content" Value="Done" />
        <Button Name="btn" Content="Start" Click="btn_Click_1" />

The code behind:

Imports System.Threading

Class MainWindow
    Private i As Integer = 0

    Private Async Sub btn_Click_1(sender As Object, e As RoutedEventArgs)
        i += 1

        Await Task.Run(Sub()
                       End Sub)

        i -= 1
        lbl.Content = i
    End Sub
End Class

The cause seems to be the data type (Integer) even if the Value property uses the Object data type and should be able to work with Integers.

Because I do not know how to handle this I appreciate any help. Thanks!

What I have tried:

I tried to convert the Integer to String. Even if I create a separate String variable and take the value from there it doesn´t work:

Private i As Integer = 0
Private si As String = ""
i -= 1
si = i.ToString()
lbl.Content = si
Updated 7-Feb-20 1:45am
Richard Deeming 7-Feb-20 6:35am    
Await Task.Run(Sub()
End Sub)

Don't do that! You're spinning up a new thread just to have it sleep for two seconds.

Instead, use:
Await Task.Delay(2000)

It's less code, it's easier to read, and it's more efficient.
Michael____ 7-Feb-20 6:46am    
thanks for the hint, the Sleep was only an example to see what happens ;-)
Richard Deeming 7-Feb-20 6:37am    
Also, I'm not convinced by the idea of using a trigger on the Content property to alter the Content property every time the Content property changes.

You'd be better off using a binding with a value converter:
How to: Convert Bound Data - WPF | Microsoft Docs[^]
Gerry Schmitz 7-Feb-20 20:48pm    
Content is either a string or a UIElement; a pure int is neither.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900