简体   繁体   中英

Windows Phone IValueConverter Issue

I can't get it to work with the IValueConverter for Windows Phone 7.0. Here is my XAML code for the binded element:

<TextBlock Text="{Binding Verified, Converter={StaticResource TextConverter}}" HorizontalAlignment="Left" VerticalAlignment="Bottom" FontSize="14" />

Here is the codebehind of the XAML file.

public class TextConverter : System.Windows.Data.IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if ((bool)value == false)
        {
            return ("Verified is False!");
        }
        if ((bool)value == true)
        {
            return ("Verified is True!");
        }
        else
        {
            return ("Error!");
        }
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
}

It think that this is right but it seems like the application can't even find the TextConverter class, do i have do declare it somewhere? When i run this application i get an Application_UnhandledException . I hope someone can help me out, thanks.

You have to add the Converter to the resources:

If you want to use it throughout your app put it in App.xaml

<Application
    ....
    ....
    xmlns:converter="clr-namespace:NAMESPACE;assembly=ASSEMBLY">

<Application.Resources>
    <converter:TextConverter x:Key="TextConverter"/>
</Application.Resources>

If you want it in a single Window put it in [Window].xaml

<Window
    ....
    ....
    xmlns:converter="clr-namespace:NAMESPACE;assembly=ASSEMBLY">

<Window.Resources>
    <converter:TextConverter x:Key="TextConverter"/>
</Window.Resources>

Make sure you change NAMESPACE and ASSEMBLY to what yours is

in order to use your class in XAML, you have to add it to your resources. So first, declare the namespace of your Converter in XAML (where the other namespaces are declared):

xmlns:src="clr-namespace:MyNameSpace"

The add your Converter to the resources section. The first element in your PhoneApplication page then would be:

<Control.Resources>
    <src:TextConverter x:Key="myConverter"/>
</Control.Resources>

Then you can access your class via its key:

... Text="{Binding Verified, Converter={StaticResource myConverter}}" ...

Nico

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM