[英]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.