[英]How can I make a multi-colored segmented progress bar in wpf?
我正在尝试创建一个充当分段进度条的 UserControl。 输入将是一组对象,每个对象都有一个类别、一个持续时间属性和状态属性。 UserControl 应该拉伸父控件的宽度和高度。 集合中的每一项都应该代表进度条的一部分; 段的颜色与状态有关,段的宽度与持续时间有关,段上覆盖的文本将与类别相关。
文本可能是集合项的 ID,顶部段颜色将与状态相关,底部颜色将与类别相关,宽度与持续时间相关。
我考虑过的一些选择:
无论哪种方式,我都会交叉手指,有人可能知道我的问题的简单解决方案。
这是自定义进度条的完整解决方案。
代码在这里: http : //1drv.ms/1QmAVuZ
1 . 如果所有步骤的宽度都不相同,我更喜欢使用带有列和不同宽度的 Grid
列是基于以下类动态构建的:
public class StepItem
{
public int Length { get; set; }
public int Index { get; set; }
public String Label { get; set; }
public Brush Brush { get; set; }
}
2.我选择实现一个CustomControl并继承ItemsControl
CustomControl 因为我不想处理Progressbar
模板部分的实现。
ItemsControl
因为:
- 我想向ItemsSource
属性提供StepItems
的集合
- ItemsControl
可以有一些DataTemplate
作为每个项目的模板
- ItemsControl
可以有任何像Grid
这样的Panel
作为模板来呈现项目的集合
3. 组件在 Generic.xaml 中有模板
-layoutGrid 将有“连续彩虹”
-overlayGrid 将根据进度部分显示在步骤上或完全显示(如果没有进度)
- ItemsPresenter
将呈现每个StepItem
对应的DataTemplates
的集合
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ProgressItemsControl}">
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid x:Name="layoutGrid">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
<Grid x:Name="overlayGrid" Width="100" HorizontalAlignment="Right" Background="White"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
4. 自定义 ItemsPanel 以使用网格(而不是垂直布局)
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate >
<Grid x:Name="stepsGrid" IsItemsHost="True" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
5. 组件代码中,列宽的设置
int i = 0;
foreach (StepItem stepItem in ItemsSource)
{
total += stepItem.Length;
var columnDefinition = new ColumnDefinition() { Width = new GridLength(stepItem.Length, GridUnitType.Star) };
stepsGrid.ColumnDefinitions.Add(columnDefinition);
Grid.SetColumn(stepsGrid.Children[i], stepItem.Index);
i++;
}
6. 用于声明可监控的依赖属性的代码
(摘抄)
public int Value
{
get { return (int)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
// Using a DependencyProperty as the backing store for Value. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(int), typeof(ProgressItemsControl), new PropertyMetadata(0));
7. 组件的使用
<local:CustomProgressBar
x:Name="customProgressBar1"
HorizontalAlignment="Left" Height="50" Margin="32,49,0,0"
VerticalAlignment="Top" Width="379"/>
8. 为组件提供数据
private List<StepItem> stepItems = new List<StepItem>{
new StepItem{
Index=0,
Label="Step1",
Length=20,
Brush = new SolidColorBrush(Color.FromArgb(255,255,0,0)),
new StepItem{
Index=4,
Label="Step5",
Length=25,
Brush = new SolidColorBrush(Color.FromArgb(255,0,128,0)),
},
};
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
progressItemsControl1.ItemsSource = stepItems;
}
问候
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.