假设您的数据类是这样的:
public class TimeLineEntry
{
public string Name { get; set; }
public DateTime Start { get; set; }
public int Index { get; set; }
public int Duration { get; set; }
}
你可以使用
ItemsControl
以矩形布局条目。
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas IsItemsHost="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="{x:Type ContentPresenter}">
<Setter Property="Canvas.Left" Value="{Binding Path=Start, Converter={StaticResource timeToPositionConverter}}" />
<Setter Property="Canvas.Top" Value="{Binding Path=Index, Converter={StaticResource indexToPositionConverter}}" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="TimeLineEntry">
<Rectangle Width="{Binding Duration}" Height="10" ToolTip="{Binding Name}" Fill="Red" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
在上面的XAML代码中,itemsControl(即基类ListBox、ListView等)的面板更改为
Canvas
以便更好地定位物品。
可以使用itemsControl.itemTemplate自定义项的显示方式。
我已经将TimelineEntry类的Start和Index属性绑定到Canvas.Left和Canvas.Top附加的ItemContainer属性,并且我还使用值转换器将日期时间值转换为像素位置。
值转换器的代码很简单。
public class IndexToPositionConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is int)
{
return ((int)value) * 10;
}
return 0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}