Search code examples
c#wpfxamldata-bindingtextblock

WPF: How to use an integer (from C#-Code) inside a TextBlock?


So basically I have an integer textlength and it has a number of symbols. I then want to output the number of symbols onto a TextBlock/Label, so that the user can see, how many symbols he used. Is there a way of implementing this without "Binding"? I really dont know much about binding, but if it is necessary to use it, it is alright as well!! Here is my simple code: C#:

...
var textlength = text.Length;
...

XAML:

<TextBlock x:Name="MyTextBlock" Width="30" Height="28" Text=" . . . " />

I want the TextBlock to operate just as a usual console --> output the value of the textlength, by saying: "The number of symbols: ..."

Thank you a lot in advance!


Solution

  • The easiest way of doing this is by implementing your own DependencyProperty. I haven't touched WPF in a few years, but if I remember correctly, it should look something like this:

    public static readonly DependencyProperty TextLengthProperty = DependencyProperty.Register(
        "TextLength", typeof(int),
        typeof(YourControlType)
        );
    
    public int TextLength
    {
        get => (int)GetValue(TextLengthProperty );
        set => SetValue(TextLengthProperty , value);
    }
    

    And the binding would look something like this:

    <TextBlock Text={Binding Path=TextLength, ElementName=nameOfParentControl}/>
    

    Then you can directly update the TextLength property, and the TextBlock will be updated automatically.

    I haven't tested this code, but it should give you a rough idea of what you need to do. Also, here's the documentation about data binding and custom dependency properties.

    If you really want to avoid data binding, you could manually update the content of the TextBlock in an event to reflect the new value of text.Length. But keep in mind that this is not a recommended way of doing it, and learning about bindings instead will benefit you in the future!