bra*_*ing 13 c# wpf xaml valuetuple
如果我有一个viewmodel属性
public (string Mdf, string MdfPath) MachineDefinition { get; set; }
Run Code Online (Sandbox Code Playgroud)
我尝试在XAML/WPF中绑定它
<Label Content="{Binding Path=MachineDefinition.Item2}" />
Run Code Online (Sandbox Code Playgroud)
要么
<Label Content="{Binding Path=MachineDefinition.MdfPath}" />
Run Code Online (Sandbox Code Playgroud)
我犯了同样的错误
我看到ValueTuple字段实际上是字段而不是属性.这是问题吗?
bra*_*ing 22
令人困惑的是,对于旧式Tuple(前C#7),所有项目都是属性
https://msdn.microsoft.com/en-us/library/dd386940(v=vs.110).aspx
因此可绑定.对于ValueTuple,它们是字段
而且不可绑定.
如果你谷歌"WPF元组绑定"你会得到大量误报,因为旧样式元组是可绑定的,但新的元组不是.
小智 6
您可以尝试实现一个值转换器。这是一个例子
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}" />
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。