Is it possible to bind to a ValueTuple field in WPF with C#7

一世执手 提交于 2019-11-29 13:13:59

The confusion is that for old style Tuple ( pre C#7 ) all the Items were properties

https://msdn.microsoft.com/en-us/library/dd386940(v=vs.110).aspx

and thus bindable. For ValueTuple they are fields

https://github.com/dotnet/corefx/blob/master/src/System.ValueTuple/src/System/ValueTuple/ValueTuple.cs#L291

and not bindable.

If you google "WPF Tuple Binding" you get loads of false positives because old style tuples are bindable but the new ones are not.

Something you could try is to implement a value converter. Here is an example...

public class TupleDisplayNameConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var tuple = value as (Int32 Id, String Name)?;

        if (tuple == null)
            return null;

        return tuple.Value.Name;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}


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

Hope this helps.

Marc Gravell

The MdfPath approach will never work, since the name part is very restrictive in terms of where it actually exists. Essentially, it is pure compiler voodoo, and doesn't exist in the type model, which means that anything that talks to the type model (which includes reflection, UI tools, serializers, etc) will only see the Item1, Item2 names; not the fake names.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!