绑定到“object.GetType()”? [英] Binding to the "object.GetType()"?

查看:146
本文介绍了绑定到“object.GetType()”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个

ObservableCollection<object>

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

Let's consider we have 2 items in it :

int a = 1;
string str = "hey!";

我的xaml文件通过DataContext访问,我想显示Type(System.Type )的对象与绑定。
这是我有的代码

My xaml file acces to it via DataContext and I'd like to display the Type (System.Type) of the object with a Binding. Here is the code I have

<TextBlock Text="{Binding}"/>

我想显示在我的TextBlocks是:

And I'd like to display in my TextBlocks is :

int
string

感谢任何帮助!

推荐答案

您需要使用 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();
    }
}

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



Then add it to your resources...

<Window.Resources>
    <my:ObjectToTypeConverter x:Key="typeConverter" />
</Window.Resources>

然后在绑定上使用它

<TextBlock Text="{Binding Mode=OneWay, Converter={StaticResource typeConverter}}" />

这篇关于绑定到“object.GetType()”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆