2010-03-15 32 views

回答

3

根据您的要求,可能会采取一系列不同的方法。以下是非常通用的解决方案。

创建一个值转换器,一个字符串转换为一个类型: -

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 
} 

将这个转换器中的目标对象具有可见性资源字典的一个实例,说的App.xaml: -

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

现在在XAML中,你可以赋值给这样的特性: -

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

我有一个例外当我使用自定义类型时,如果我没有指定版本,但你的解决方案似乎是我们能做的最好的:( – 2010-03-17 09:00:00

+0

@Nicolas Dorier:对于自定义类型,请尝试仅使用类型名称(而不是添加版本号,删除程序集名称)。如果自定义类型与使用此技术的Xaml/Usercontrol在同一个程序集中,则应该可以工作。 – AnthonyWJones 2010-03-17 09:26:39

2

另一种方法是用类型转换器来装饰属性本身。

定义这样的类型转换器:

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"/> 
相关问题