我的模型看起来像这样:
class Puzzle
{
public string Name {get; set;}
public string Id {get; set;}
public PuzzleKind Kind {get; set;}
public Dictionary<string, string> Details {get; set;}
}
详细信息字段与我的不同拼图不同。在那些我使用DateTemplateSelector的UI表示中,根据PuzzleKind选择使用一个或另一个数据模板的模板。它就像一个魅力。
我绑定了Name,Id和Kind,没问题。我的问题是如何绑定到详细信息[“密钥”]?
我知道什么样的细节会根据拼图类型到达,我创建了一个这样的DataTemplate:
<DataTemplate x:Key="myFirstTemplate">
<ViewCell>
<Grid ... with definitions...>
<Label Text="{Binding Path=Details["expectedKey"],
Converter={StaticResource myConverter}}"/>
</Grid>
</ViewCell>
</DataTemplate>
此代码只是在启动期间抛出和未处理的异常...我的问题是如何绑定到此,以及如何根据incomming值更改字体的颜色
细节[expectedKey](没有引号)对我有用...
如果“expectedKey”是硬编码的,那么你可以通过下一个方式完成:
<Label Text="{Binding Path=Details.[expectedKey]}" />
语法有点棘手,但并不是那么糟糕。
您还可以通过下一个方式遍历Dictionary:
<ListView
ItemsSource="{Binding Details}">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Key}" Detail="{Binding Value}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
我最终只是绑定到json并在转换器中使用参数来了解需要使用的预期参数。像这样:
<Label Text="{Binding Path=Details, Converter={StaticResource FirstClockConverter}, ConverterParameter=expectedKey}"/>
然后在后面的代码我处理这样的事情:
public class FirstClockConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (value as Dictionary<string,string>)[parameter as string];
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
这里的好处是我可以根据参数调整转换(知道expectedParamenter的类型,或者我甚至可以检查主模型的静态属性中的其他值,以便在屏幕上显示正确的反馈。只有一个转换器对于所有绑定。