开发者

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

开发者 https://www.devze.com 2022-12-23 02:33 出处:网络
I\'d like to know how I can assign in XAML a dependency property of type Type in Silverlight since the markup e开发者_StackOverflow中文版xtension {x:Type} does not exist ?

I'd like to know how I can assign in XAML a dependency property of type Type in Silverlight since the markup e开发者_StackOverflow中文版xtension {x:Type} does not exist ?

Thanks,


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}}" />


Another approach is to decorate the property itself with a type converter.

Define a TypeConverter like this:

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;
   }
}

Decorate your property like this:

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

And then in your XAML you can do this:

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

精彩评论

暂无评论...
验证码 换一张
取 消