2011-11-19 106 views
2

我打算創建一個自定義進度欄控件,該控件支持進度切片。最終的外觀將是:帶有圓角的自定義Silverlight進度條控件

progress bar with sections

我是比較新的Silverlight控件開發,所以這裏是我的想法和問題:

  1. 我會被定義在XAML控制的結構作爲ItemsControl
  2. ItemsControl元素將被綁定到數據源,該數據源將包含條形截面。
  3. ItemTemplate將定義繪製這些部分的方式。

「訣竅」是,第一個和最後一個部分分別應該有一個左右圓角。我怎樣才能定義這個約束,以便源頭的第一個和最後一個項目都是用圓角繪製的?我可以在XAML或代碼中做到這一點嗎?如果代碼,我在哪裏注入邏輯?

回答

1

您可以創建一個邊框列表,從列表中取第一個和最後一個邊框並應用角半徑。

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:AchievedConverter x:Key="AchievedConverter"/> 
    </Window.Resources> 
    <Grid> 
     <ListBox Name="listBox" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemsSource="{Binding Bars}"> 
      <ListBox.ItemsPanel> 
       <ItemsPanelTemplate> 
        <WrapPanel IsItemsHost="True" /> 
       </ItemsPanelTemplate> 
      </ListBox.ItemsPanel> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <Border Height="10" CornerRadius="{Binding Corner}" Width="{Binding Width}" Background="{Binding IsAchieved, Converter={StaticResource AchievedConverter}}"/> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 
    </Grid> 
</Window> 

C#:

/// <summary> 
/// Interaction logic for MainWindow.xaml 
/// </summary> 
public partial class MainWindow : Window 
{ 
    private ObservableCollection<Bar> _bars; 

    public MainWindow() 
    { 
     InitializeComponent(); 
     this.DataContext = this; 

     _bars = new ObservableCollection<Bar>(); 

     //Init 
     _bars.Add(new Bar {Width = 20, IsAchieved = true, Corner = new CornerRadius(5, 0, 0, 5)}); 
     _bars.Add(new Bar {Width = 60, IsAchieved = true}); 
     _bars.Add(new Bar {Width = 80, IsAchieved = true}); 
     _bars.Add(new Bar {Width = 20, IsAchieved = false}); 
     _bars.Add(new Bar {Width = 50, IsAchieved = false, Corner = new CornerRadius(0, 5, 5, 0)}); 
    } 

    public ObservableCollection<Bar> Bars 
    { 
     get { return _bars; } 
    } 
} 

public class Bar 
{ 
    public double Width { get; set; } 
    public bool IsAchieved { get; set; } 
    public CornerRadius Corner { get; set; } 
} 

public class AchievedConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if ((bool)value) 
      return new SolidColorBrush(Colors.Green); 
     else 
      return new SolidColorBrush(Colors.Red); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

enter image description here

+0

呀,謝謝你,但問題是我怎麼 「從列表中採取的第一個和最後一個邊界」? –

+0

我附上了一個樣本。它應該幫助你。 –

+0

正如我所說,項目的數量將始終是可變的,並綁定到一個集合。但是你建議在代碼背後進行四捨五入的構造函數。好吧,我會試着回到這個問題上。謝謝。 –