How to create a dependency property of type Type and assign it in XAML?

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

Thank,

+3
source share
2 answers

A number of different approaches may exist depending on your requirement. The following is a very general solution.

Create a value converter that converts the string to 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
}

Put an instance of this converter in the resource dictionary for which the target object is visible, say, App.xaml: -

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

Now in your Xaml you can assign a value to the following properties: -

 <TextBox Text="{Binding Source='System.Int32,mscorlib', Converter={StaticResource STT}}" />
+3
source

, .

TypeConverter :

public class StringToTypeConverter : TypeConverter
{
   public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
   {
     return sourceType.IsAssignableFrom(typeof (string));
   }

   public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
   {
      var text = value as string;
      return text != null ? Type.GetType(text) : null;
   }
}

:

[TypeConverter(typeof(StringToTypeConverter))]
public Type MessageType
{
    get { return (Type) GetValue(MessageTypeProperty); }
    set { SetValue(MessageTypeProperty, value); }
}

XAML :

<MyObject MessageType="My.Fully.Qualified.Type"/>
+2

Source: https://habr.com/ru/post/1736962/


All Articles