views:

33

answers:

1

I'd like to know how I can assign in XAML a dependency property of type Type in Silverlight since the markup extension {x:Type} does not exist ?

Thanks,

+2  A: 

Depending on your requirement there may be a range of different approaches to take. The following is very general solution.

Create a value converter which converts a string to a Type:-

public class StringToTypeConverter : IValueConverter
{

    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Type.GetType((string)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

Place an instance of this converter in resource dictionary of which destination object has visibility, say the App.xaml:-

    <Application.Resources>
        <local:StringToTypeConverter x:Key="STT" />
    </Application.Resources>

Now in your Xaml you can assign a value to a property like this:-

 <TextBox Text="{Binding Source='System.Int32,mscorlib', Converter={StaticResource STT}}" />
AnthonyWJones
I have an exception when I use it on custom type if I don't specify the version, but your solution seems to be the best we can do :(
Nicolas Dorier
@Nicolas Dorier: For a custom type try just using the type name alone (that is instead of adding a version number, remove the assembly name). If the custom type is in the same assembly as your Xaml/Usercontrol that is using this technique that should work.
AnthonyWJones