Search code examples
c#xaml

Why am I getting a 'Cannot find resource named 'GUIDConverter'' error when running my XAML program?


I have an Xaml page that uses a binding convert to convert a GUID to a string however when running the program I get the following error:

Exception: Cannot find resource named 'GUIDConverter'. Resource names are case sensitive.

I have the IValueConverter interface as

public class GUIDConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string? strGuid;
            try
            {
                strGuid = value.ToString();
            }
            catch (Exception)
            {
                return string.Empty;
                throw;
            }
            
            return strGuid;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Guid? OldGuid;
            try
            {
                OldGuid = Guid.Parse(value.ToString());
            }
            catch (Exception)
            {
                return Guid.Empty;
            }
            return OldGuid;
        }
    }

and referencing it in the App.Xaml as:

<Application ...
             xmlns:super="clr-namespace:DatabaseTest">
    <Application.Resources>
        <super:GUIDConverter x:Key="GUIDConverter"/>
    </Application.Resources>
</Application>

and finally, I added the converter like so:

                        <ListView.View>
                            <GridView>
                                <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ElementName=customerID, Converter={StaticResource GUIDConverter}, ConverterParameter=Normal}"/>
                                <GridViewColumn Header="FirstName" DisplayMemberBinding="{Binding firstName}"/>
                            </GridView>
                        </ListView.View>

I'm not really sure why this isn't working as it seems to be written the correct way, I'd appreciate any help

(Also, I am using Mah:Metro)


Solution

  • You have to put the reference in a ResourceDictionary if you want to make it accessible in the StaticStaticResources like this:

    <Application ...
        xmlns:super="clr-namespace:DatabaseTest">
        <Application.Resources>
            <ResourceDictionary>
                <super:GUIDConverter x:Key="GUIDConverter" />
            </ResourceDictionary>
        </Application.Resources>
    </Application>
    

    Or if you need it only in the place you're using the ListView you can insert the reference in the Window.Resources