Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Textblock Convert Issue

Tags:

wpf

textblock

am usina text block in usercontrol, but am sending value to textblock from other form, when i pass some value it viewed in textblock, but i need to convert the number to text. so i used converter in textblock. but its not working

 <TextBlock Height="21" Name="txtStatus" Width="65" Background="Bisque" TextAlignment="Center" Text="{Binding Path=hM1,Converter={StaticResource TextConvert},Mode=OneWay}"/>

converter class

class TextConvert : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {

        if (value != null)
        {
            if (value.ToString() == "1")
            {
                return value = "Good";

            }
            if (value.ToString() == "0")
            {
                return value = "NIL";

            }

       }
        return value = "";
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (string)value;
    }

}

is it right? whats wrong in it??

like image 924
Spen D Avatar asked Jul 21 '26 00:07

Spen D


2 Answers

ok I think I know what the problem is - let see if I can define it for you :)

in your xaml file where you want to use TextConvert, define Resource for it (unless you are doing it already, then I haven't a clue why its not working)

    <Grid.Resources>
        <Shared:TextConvert x:Key="TextConvertKey" />
    </Grid.Resources>

shared being the xmlns ofcourse.

Then in the textbox use it like:

Text="{Binding Path=hM1,Converter={StaticResource TextConvertKey},Mode=OneWay}"/>

EDIT:

If you set a breakpoint in the converter class, does the debugger go in there?????

EDIT 2:

am using like this voodoo

local:HealthTextConvert x:Key="TextConvert"

This is absolutely wrong. How can you Call it HealthTextConvert when the converter name is TextConvert???

it should be

local:TextConvert x:Key="whateverKeyNameYouWant"

and

in the textbox is should be

Text="{Binding Path=hM1,Converter={StaticResource whateverKeyNameYouWant},Mode=OneWay}"
like image 54
VoodooChild Avatar answered Jul 23 '26 22:07

VoodooChild


I can see immediately a problem with your converter definition.

class TextConvert : IValueConverter
{
    ...

Should be declared public to be able to use it as a resource.

public class TextConvert : IValueConverter
{
    ...

Also, its not a good thing to be doing this...

return value = "Good";

...

return value = "NIL";

It should just be (even though it will not matter if you leave it, just bad programming =P):

return "Good";

...

return "Nill";
like image 20
Tri Q Tran Avatar answered Jul 23 '26 22:07

Tri Q Tran