WPF 绘制垂直刻度尺,两边是刻度线,中间是进度条,请用WPF实现
时间: 2024-10-12 19:00:32 浏览: 41
在WPF中实现一个带有刻度线的垂直进度条,可以利用`StackPanel`、`Rectangle`、`TextBlock`和`Track`等元素结合样式和数据模板来构建。以下是一个简化的步骤和示例代码:
1. 创建XAML布局:
```xml
<Window x:Class="VerticalScaleProgress"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<!-- 刻度线 -->
<StackPanel Grid.Column="1" Orientation="Horizontal" HorizontalAlignment="Stretch">
<Rectangle Height="10" Fill="#A8A8A8" Margin="5,0,0,0" Stroke="#000000" StrokeThickness="1" />
<!-- 添加更多刻度线... -->
</StackPanel>
<!-- 进度条 -->
<Track Grid.Column="1" Name="progressBar" Minimum="0" Maximum="100" Value="50">
<Track.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#E0E0E0" Offset="0"/>
<GradientStop Color="Transparent" Offset="1"/>
</LinearGradientBrush>
</Track.Background>
<Track.Tracks >
<Ellipse Width="4" Height="20" Fill="{Binding Progress, RelativeSource={RelativeSource AncestorType=Track}}" Canvas.Left="{Binding Path=Value, RelativeSource={RelativeSource AncestorType=Track}, Converter={StaticResource ValueToPositionConverter}}"/>
</Track.Tracks>
</Track>
<!-- 左右刻度标签 -->
<TextBlock Grid.Column="0" Text="0%" VerticalAlignment="Center" />
<TextBlock Grid.Column="2" Text="100%" VerticalAlignment="Center" />
</Grid>
</Window>
```
2. 创建ValueToPositionConverter:
```csharp
public class ValueToPositionConverter : MarkupExtension, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is int trackValue && progressBar != null)
return progressBar.ActualWidth * ((double)trackValue / (double)progressBar.Maximum);
return 0;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
// 如果在设计时间,这个属性将为空
progressBar = (Track)GetValue(progressBarProperty);
return this;
}
public static readonly DependencyProperty progressBarProperty = DependencyProperty.RegisterAttached("ProgressBar", typeof(Track), typeof(ValueToPositionConverter), new PropertyMetadata(null));
}
```
3. 配置资源和窗体:
在`App.xaml`或`Window.Resources`中注册`ValueToPositionConverter`。
现在,当进度条值改变时,刻度线会动态更新位置,并显示相应的百分比标签。你可以通过代码绑定或者控件属性设置来控制进度条值的变化。
阅读全文