绑定到"object.GetType()"?

Gui*_*shy 3 data-binding wpf xaml

我有一个

ObservableCollection<object>
Run Code Online (Sandbox Code Playgroud)

我们考虑我们有2个项目:

int a = 1;
string str = "hey!";
Run Code Online (Sandbox Code Playgroud)

我的xaml文件通过DataContext访问它,我想用Binding显示对象的Type(System.Type).这是我的代码

<TextBlock Text="{Binding}"/>
Run Code Online (Sandbox Code Playgroud)

而我想在我的TextBlocks中显示:

int
string
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助 !

Ada*_*son 11

您需要使用a IValueConverter来执行此操作.

[ValueConversion(typeof(object), typeof(string))]
public class ObjectToTypeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value == null ? null : value.GetType().Name // or FullName, or whatever
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new InvalidOperationException();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将其添加到您的资源中......

<Window.Resources>
    <my:ObjectToTypeConverter x:Key="typeConverter" />
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

然后在绑定上使用它

<TextBlock Text="{Binding Mode=OneWay, Converter={StaticResource typeConverter}}" />
Run Code Online (Sandbox Code Playgroud)