【问题标题】:Binding to the "object.GetType()"?绑定到“object.GetType()”?
【发布时间】:2011-11-23 15:23:14
【问题描述】:

我有一个

ObservableCollection<object>

假设我们有 2 个项目:

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

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

<TextBlock Text="{Binding}"/>

我想在我的 TextBlocks 中显示的是:

int
string

感谢您的帮助!

【问题讨论】:

  • 请注意,仅使用 Type.Name 您将获得“Int32”和“String”。如果要使用 C# 短名称,则需要在 ValueConverter 中编写自己的函数(如其他人所述),以将 Type 映射到短名称。不幸的是,没有内置功能可以做到这一点。不过,您也许可以找到其他人编写的一些函数。

标签: wpf xaml data-binding


【解决方案1】:

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

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

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

然后在你的绑定上使用它

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 2011-10-03
    • 2016-01-01
    • 2019-05-21
    • 2011-03-16
    • 2016-07-02
    • 1970-01-01
    相关资源
    最近更新 更多