我需要使用单个DataTemplate绘制多行,如下所示
<DataTemplate x:Key="MultilineDataTemplate">
<Line X1="{Binding X1}" Y1="{Binding Y1}" X2="{Binding X2}" Y2="{Binding Y2}" Fill="Red"
StrokeThickness="2" Stroke="Black" />
</DataTemplate>
其中X1,Y1,X2,Y2是坐标数组。
我想知道是否可以使用该DataTemplate。
答案 0 :(得分:2)
您可以使用IValueConverter将多个数组转换为可绑定对象列表。
public class ArrayCoordinateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
ViewModelClassHere viewModel = (value as ViewModelClassHere);
if (viewModel != null)
{
// Assuming that X1 will always have cooresponding elements in X2, Y1, Y2;
var enumerable = viewModel .X1.Select((x, i) => new
{
X1 = x,
X2 = viewModel.X2[i],
Y1 = viewModel.Y1[i],
Y2 = viewModel.Y2[i]
});
return enumerable;
}
return null;
}
public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
<强>用法:强>
<ItemsControl ItemsSource="{Binding Converter={StaticResource arrayCoordinateConverter}}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas IsItemsHost="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Line X1="{Binding X1}"
Y1="{Binding Y1}"
X2="{Binding X2}"
Y2="{Binding Y2}"
Fill="Red"
StrokeThickness="2"
Stroke="Black" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>