Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type conversion in xaml

Tags:

c#

wpf

xaml

I'm new to WPF and am finding a surprisingly scarce amount of information regarding what I thought was a basic problem, which is to use an integer for the text in a TextBlock. Here is how I defined my resources in app.xaml:

xmlns:sys="clr-namespace:System;assembly=mscorlib"

and

<Application.Resources>
    <sys:Int32 x:Key="MyResourceName">-1</sys:Int32>
</Application.Resources>

This is correctly defined and functional because VS locates in when I try to use it in a simple TextBlock object:

<TextBlock Name="MyTextboxName" Text="{DynamicResource MyResourceName}" />

The problem is that it generates an error explaining, of course, that it can't convert an integer to a string by default. Normally, I would cast it before I knew I was typing, but I don't know how to cast in xaml. I considered binding, but it doesn't seem to be focused around user-defined variables as much and would be more cumbersome, so then I looked at converters. I also found little about converting integers to strings in xaml. If there isn't a solution, I can simply make the variables strings and convert them to integers or floats only for conversions, then convert them back, but that would be a major (and messy) pain.

Edit: To be clear, I'm really asking two questions:

  1. Is type conversion possible in only Xaml?
  2. Is there a default converter for converting one primitive type to another?

1 Answers

There already is in the Framework a TypeConverter that converts an int to a string, the issue here is that it is not applied when you are using the StaticResource or DynamicResource.

You just have to bind to your resource:

<TextBlock Name="MyTextboxName" Text="{Binding Source={StaticResource MyResourceName}}" />

You cannot use DynamicResource though.

like image 184
Novitchi S Avatar answered Sep 13 '26 18:09

Novitchi S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!