WPF - Drawing image to canvas and erasing and redrawing repeatedly
I currently have a canvas with an image background in a WPF application. Above this canvas, I have a slider control. I need to, as users slide the value of the slider back and forth, draw a red line straight down across the canvas. I need to do this every time the slider value is changed such that the red line is always aligned with the slider's thumb. The big problem I'm having here is trying to figure out how to efficiently draw the line, and then "erase" the previously drawn line and drawing a new line at the new thumb value when user's change the slider's value. If I simply redraw the canvas's background image, the application lags a lot and doesn't work well (plus, this just straight out doesn't completely solve the problem as you can still see the previously drawn lines anyway).
Any help would be absolutely appreciated, parti开发者_开发问答cularly with examples as I this is my first WPF application in C# and I'm stilling getting a feel for it's uniqueness (as opposed to Windows Forms). Thanks a lot!
Rather than trying to draw the line yourself, a more WPF way to approach it would be to use a Line object. See Shapes and Basic Drawing in WPF Overview. Since you want the line to be aligned with the Slider, you can use data binding to bind the X position of the line to the position of the Slider:
<DockPanel>
<Slider
Name="HorizontalSlider"
DockPanel.Dock="Top"
Maximum="{Binding ActualWidth, ElementName=Canvas}"/>
<Canvas Name="Canvas" Margin="5.5 0">
<Line
X1="{Binding Value, ElementName=HorizontalSlider}"
Y1="0"
X2="{Binding Value, ElementName=HorizontalSlider}"
Y2="{Binding ActualHeight, RelativeSource={RelativeSource AncestorType=Canvas}}"
Stroke="Red"/>
</Canvas>
</DockPanel>
(Note that I cheated a little by setting the margin on the Canvas to 5.5. The thumb on the slider has some thickness and doesn't move the entire width of the slider control, so in order to get the line to line up with the center I tried to make the canvas have the same width as the track.)
精彩评论