c# – 如何在WPF中动态绘制时间轴

前端之家收集整理的这篇文章主要介绍了c# – 如何在WPF中动态绘制时间轴前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在 WPF中绘制时间表.它应该基本上由3个矩形组成.

它应该看起来像这样(使用XAML硬编码):
Timeline

大的白色矩形应填充所有可用空间,绿色矩形表示在时间轴上发生的事件的开始和持续时间.

表示此模型的模型是TimeLineEvent类,它具有TimeSpan开始和时间跨度持续时间,以表示事件何时开始以及持续多长时间(以滴答或秒或其他为单位).还有一个TimeLine类,它有一个ObservableCollection,用于保存时间轴上的所有事件.它还有一个TimeSpan持续时间,表示时间轴本身的长度.

我需要做的是能够根据它们的持续时间和开始动态绘制时间轴上的事件(绿色矩形),以及它们之间的比率,以便绘制与事件发生时间和持续时间相对应的事件.时间轴上可以有多个事件.

到目前为止,我的方法是创建一个仅包含canvas元素的TimeLine.xaml文件.在代码隐藏文件中,我重写了OnRender方法来绘制这些矩形,这些矩形适用于硬编码值.

在MainWindow.xaml中,我创建了一个datatemplate并将数据类型设置为TimeLine:

  1. <DataTemplate x:Key="TimeLineEventsTemplate" DataType="{x:Type local:TimeLine}">
  2. <Border>
  3. <local:TimeLine Background="Transparent"/>
  4. </Border>
  5. </DataTemplate>

尝试了不同的设置,但不确定我要做的是说实话.然后我有一个stackpanel,它包含一个列表框,它使用我的datatemplate和绑定TimeLines,它是一个ObservableCollection,包含TimeLine对象,在我的MainWindow代码隐藏中.

  1. <StackPanel Grid.Column="1" Grid.Row="0">
  2. <ListBox x:Name="listBox"
  3. Margin="20 20 20 0"
  4. Background="Transparent"
  5. ItemTemplate="{StaticResource TimeLineEventsTemplate}"
  6. ItemsSource="{Binding TimeLines}"/>
  7. </StackPanel>

当我创建新的Timeline对象时,这会绘制新的时间轴,如下所示:
Timelines

这个问题是它没有正确渲染绿色矩形,为此我需要知道白色矩形的宽度,这样我就可以使用不同持续时间的比率转换到一个位置.
问题似乎是在调用OnRender方法时width属性为0.我试过重写OnRenderSizeChanged,如下所示:In WPF how can I get the rendered size of a control before it actually renders?
我在调试打印中看到OnRender首先被调用,然后是OnRenderSizeChanged然后我通过调用this.InvalidateVisual()来让OnRender再次运行.在覆盖中.我可以得到的所有宽度属性仍然总是0虽然这很奇怪,因为我可以看到它被渲染并具有大小.还尝试了其他帖子中显示的测量和排列覆盖,但到目前为止还没有能够获得除0以外的值.

那么如何在时间轴上以正确的位置和大小动态绘制矩形呢?

对不起,如果我遗漏了一些明显的东西,我刚刚和WPF一起工作了一个星期,我没有人问.如果您想查看更多代码示例,请与我们联系.任何帮助表示赞赏:).

解决方法

我只想说,对于刚接触WPF的人来说,你似乎对事情有了很好的把握.

无论如何,这可能是个人偏好,但我通常首先尝试尽可能地利用WPF布局引擎,然后如果绝对需要开始讨论绘图,特别是因为在确定渲染的内容时遇到的困难和什么不是,什么有宽度,什么没有,等等.

我将提出一个主要针对XAML并使用多值转换器的解决方案.与我将解释的其他方法相比,这有利有弊,但这是阻力最小的路径(无论如何努力;))

EventLengthConverter.cs:

  1. public class EventLengthConverter : IMultiValueConverter
  2. {
  3.  
  4. public object Convert(object[] values,Type targetType,object parameter,System.Globalization.CultureInfo culture)
  5. {
  6. TimeSpan timelineDuration = (TimeSpan)values[0];
  7. TimeSpan relativeTime = (TimeSpan)values[1];
  8. double containerWidth = (double)values[2];
  9. double factor = relativeTime.TotalSeconds / timelineDuration.TotalSeconds;
  10. double rval = factor * containerWidth;
  11.  
  12. if (targetType == typeof(Thickness))
  13. {
  14. return new Thickness(rval,0);
  15. }
  16. else
  17. {
  18. return rval;
  19. }
  20. }
  21.  
  22. public object[] ConvertBack(object value,Type[] targetTypes,System.Globalization.CultureInfo culture)
  23. {
  24. throw new NotImplementedException();
  25. }
  26. }

MainWindow.xaml:

  1. <Window x:Class="timelines.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:local="clr-namespace:timelines"
  5. DataContext="{Binding Source={StaticResource Locator},Path=Main}"
  6. Title="MainWindow" Height="350" Width="525">
  7. <Window.Resources>
  8. <local:EventLengthConverter x:Key="mEventLengthConverter"/>
  9. </Window.Resources>
  10. <Grid>
  11. <ItemsControl ItemsSource="{Binding Path=TimeLines}">
  12. <ItemsControl.ItemTemplate>
  13. <DataTemplate>
  14. <ItemsControl x:Name="TimeLine" ItemsSource="{Binding Path=Events}">
  15. <ItemsControl.ItemsPanel>
  16. <ItemsPanelTemplate>
  17. <Grid x:Name="EventContainer" Height="20" Margin="5" Background="Gainsboro"/>
  18. </ItemsPanelTemplate>
  19. </ItemsControl.ItemsPanel>
  20. <ItemsControl.ItemTemplate>
  21. <DataTemplate>
  22. <Rectangle Grid.Column="1" Fill="Green" VerticalAlignment="Stretch" HorizontalAlignment="Left">
  23. <Rectangle.Margin>
  24. <MultiBinding Converter="{StaticResource mEventLengthConverter}">
  25. <Binding ElementName="TimeLine" Path="DataContext.Duration"/>
  26. <Binding Path="Start"/>
  27. <Binding ElementName="EventContainer" Path="ActualWidth"/>
  28. </MultiBinding>
  29. </Rectangle.Margin>
  30. <Rectangle.Width>
  31. <MultiBinding Converter="{StaticResource mEventLengthConverter}">
  32. <Binding ElementName="TimeLine" Path="DataContext.Duration"/>
  33. <Binding Path="Duration"/>
  34. <Binding ElementName="EventContainer" Path="ActualWidth"/>
  35. </MultiBinding>
  36. </Rectangle.Width>
  37. </Rectangle>
  38. </DataTemplate>
  39. </ItemsControl.ItemTemplate>
  40. </ItemsControl>
  41. </DataTemplate>
  42. </ItemsControl.ItemTemplate>
  43. </ItemsControl>
  44. </Grid>

这是我在分别有两个和三个事件的两个时间轴时看到的.

说明

你最终得到的是嵌套的ItemsControls,一个用于顶级TimeLine属性,一个用于每个时间轴的事件.我们将TimeLine ItemControl的ItemsPanel重写为一个简单的Grid – 我们这样做是为了确保我们所有的矩形使用相同的原点(以匹配我们的数据),而不是说StackPanel.

接下来,每个事件都有自己的矩形,我们使用EventLengthConverter来计算边距(实际上是偏移量)和宽度.我们为多值转换器提供所需的一切,时间轴持续时间,事件开始或持续时间以及容器宽度.只要其中一个值发生变化,转换器就会被调用.理想情况下,每个矩形都会在网格中得到一个列,您可以将所有这些宽度设置为百分比,但我们会因数据的动态特性而失去这种奢侈.

优点和缺点

事件是元素树中自己的对象.您现在对显示事件的方式有很多控制权.它们不需要只是矩形,它们可以是具有更多行为的复杂对象.至于反对这种方法的原因 – 我不确定.有人可能会与性能争论,但我无法想象这是一个实际问题.

提示

您可以像以前一样打破这些数据模板,我只是将它们全部包含在一起,以便在答案中更容易地查看层次结构.此外,如果您希望转换器的意图更清晰,您可以创建两个,例如“EventStartConverter”和“EventWidthConverter”,并抛弃对targetType的检查.

编辑:

Mainviewmodel.cs

  1. public class Mainviewmodel : viewmodelBase
  2. {
  3. /// <summary>
  4. /// Initializes a new instance of the Mainviewmodel class.
  5. /// </summary>
  6. public Mainviewmodel()
  7. {
  8.  
  9. TimeLine first = new TimeLine();
  10. first.Duration = new TimeSpan(1,0);
  11. first.Events.Add(new TimeLineEvent() { Start = new TimeSpan(0,15,0),Duration = new TimeSpan(0,0) });
  12. first.Events.Add(new TimeLineEvent() { Start = new TimeSpan(0,40,10,0) });
  13. this.TimeLines.Add(first);
  14.  
  15. TimeLine second = new TimeLine();
  16. second.Duration = new TimeSpan(1,0);
  17. second.Events.Add(new TimeLineEvent() { Start = new TimeSpan(0,25,0) });
  18. second.Events.Add(new TimeLineEvent() { Start = new TimeSpan(0,30,50,0) });
  19. this.TimeLines.Add(second);
  20. }
  21.  
  22.  
  23. private ObservableCollection<TimeLine> _timeLines = new ObservableCollection<TimeLine>();
  24. public ObservableCollection<TimeLine> TimeLines
  25. {
  26. get
  27. {
  28. return _timeLines;
  29. }
  30. set
  31. {
  32. Set(() => TimeLines,ref _timeLines,value);
  33. }
  34. }
  35.  
  36. }
  37.  
  38. public class TimeLineEvent : ObservableObject
  39. {
  40. private TimeSpan _start;
  41. public TimeSpan Start
  42. {
  43. get
  44. {
  45. return _start;
  46. }
  47. set
  48. {
  49. Set(() => Start,ref _start,value);
  50. }
  51. }
  52.  
  53.  
  54. private TimeSpan _duration;
  55. public TimeSpan Duration
  56. {
  57. get
  58. {
  59. return _duration;
  60. }
  61. set
  62. {
  63. Set(() => Duration,ref _duration,value);
  64. }
  65. }
  66.  
  67. }
  68.  
  69.  
  70. public class TimeLine : ObservableObject
  71. {
  72. private TimeSpan _duration;
  73. public TimeSpan Duration
  74. {
  75. get
  76. {
  77. return _duration;
  78. }
  79. set
  80. {
  81. Set(() => Duration,value);
  82. }
  83. }
  84.  
  85.  
  86. private ObservableCollection<TimeLineEvent> _events = new ObservableCollection<TimeLineEvent>();
  87. public ObservableCollection<TimeLineEvent> Events
  88. {
  89. get
  90. {
  91. return _events;
  92. }
  93. set
  94. {
  95. Set(() => Events,ref _events,value);
  96. }
  97. }
  98. }

猜你在找的C#相关文章