我正在开发一个应用程序,用户可以在多个开启/关闭持续时间序列之间进行选择。序列总是以开周期开始,并且可以有不同的长度(但总是开/关对):例如
var sequences = new []
{
new int[] { 10, 15 }, // 10 ms on, 15 ms off
new int[] { 15, 10, 5, 10 } // 15 ms on, 10 ms off, 5 ms on, 10 ms off
};序列的最大持续时间为10秒,并将重复。一个特殊的序列定义了无开/关持续时间:它总是打开的(尽管我可以将其更改为{1,0}或其他值)。
我不想在屏幕上显示数字,而是显示完整10秒的图形表示(重复较短的序列),以便用户可以比较模式。它们将显示在随窗口调整大小的组合框中。对于上面的例子,它看起来像下面这样(其中X是一个填充的背景)
xx xx xx xx xx xx xx...
xxx x xxx x xxx x xxx x ...我想我将不得不使用一个值转换器(如果只针对特殊的值),但我不确定创建图形的最佳/最简单的方法是什么,特别是在需要调整大小并重复较短序列的情况下。一块画布,还是别的什么?
如果有任何建议,我将非常感谢!
发布于 2011-01-04 11:02:27
我将遵循以下基本方法:
这是一个简单的实现(没有错误处理,也没有任何美化它的尝试):
UDPATE:修复了在10秒时不能正确截断重复序列的错误。
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace TestWpf
{
public class SeqSegment
{
public bool IsOn { get; set; }
public int Duration { get; set; }
}
public class SeqConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var result = new List<SeqSegment>();
var seq = (int[]) value;
int time = 0;
int i = 0;
bool isOn = true;
while (time < 10000)
{
result.Add(new SeqSegment { Duration = Math.Min(seq[i], 10000 - time), IsOn = isOn });
isOn = !isOn;
time += seq[i];
i++;
if (i >= seq.Length)
i = 0;
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public IEnumerable<int[]> TestSequences
{
get
{
yield return new[] {10, 5000, 10, 8};
yield return new[] {500, 5000};
yield return new[] {50, 400, 30, 10};
}
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
}
}XAML:
<Window x:Class="TestWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:TestWpf="clr-namespace:TestWpf" Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<TestWpf:SeqConverter x:Key="SeqConverter"/>
<DataTemplate x:Key="SeqSegTemplate">
<Rectangle x:Name="Rect" Width="{Binding Duration}" Fill="Blue"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsOn}" Value="True">
<Setter TargetName="Rect" Property="Fill" Value="Green"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
<DataTemplate x:Key="SeqTemplate">
<Viewbox Height="50" Stretch="Fill">
<ItemsControl ItemsSource="{Binding Converter={StaticResource SeqConverter}}" ItemTemplate="{StaticResource SeqSegTemplate}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" Height="1"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Viewbox>
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding TestSequences}" ItemTemplate="{StaticResource SeqTemplate}"/>
</Grid>
</Window>https://stackoverflow.com/questions/4590193
复制相似问题