Wpf DataTemplate绘制多条线
本文关键字:绘制 DataTemplate Wpf | 更新日期: 2023-09-27 18:19:17
我需要用一个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
你可以使用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>