I'm trying to rotate then translate an image with the simple Matrix.translate and Matrix.rotate methods, but for some reason when it's rotated 90º or 270º, if I try to translate it even an inch it spins out of control and away from the center. And if it's 180º it shoots out in the opposite direction.
The xaml for the image is like so:
<Border x:Name="Border" Grid.Row="0" MinHeight="100" MinWidth="100" VerticalAlignment="Center" HorizontalAlignment="Center" ClipToBounds="True" BorderBrush="Black" BorderThickness="1" >
<Image x:Name="imgImagem" MaxHeight="550" MaxWidth="950"
Margin="10,10,10,10" MouseWheel="imgImagem_MouseWheel"
MouseLeftButtonDown="imgImagem_MouseLeftButtonDown"
/>
</Border>
For the rotation:
Private Sub imgImagem_MouseRightButtonDown(sender As Object, e As MouseButtonEventArgs) Handles imgImagem.MouseRightButtonDown
Dim m As Matrix = imgImagem.RenderTransform.Value
m.RotateAt(90, imgImagem.ActualWidth / 2, imgImagem.ActualHeight / 2)
imgImagem.RenderTransform = New MatrixTransform(m)
End Sub
And for the translation:
Private Sub imgImagem_MouseLeftButtonDown(sender As Object, e As MouseButtonEventArgs)
If imgImagem.IsMouseCaptured Then
Return
End If
imgImagem.CaptureMouse()
start = e.GetPosition(imgImagem)
origin.X = imgImagem.RenderTransform.Value.OffsetX
origin.Y = imgImagem.RenderTransform.Value.OffsetY
End Sub
Private Sub imgImagem_MouseLeftButtonUp(sender As Object, e As MouseButtonEventArgs) Handles imgImagem.MouseLeftButtonUp
imgImagem.ReleaseMouseCapture()
End Sub
Private Sub imgImagem_MouseMove(sender As Object, e As Input.MouseEventArgs) Handles imgImagem.MouseMove
Dim m As Matrix = imgImagem.RenderTransform.Value
If Not imgImagem.IsMouseCaptured Then
Return
End If
Dim p As Point = e.MouseDevice.GetPosition(imgImagem)
m.Translate((p.X - start.X), (p.Y - start.Y))
imgImagem.RenderTransform = New MatrixTransform(m)
End Sub
Any clues on what's making it spin out and such or what am I doing wrong for it to present such behavior?
Just had to differentiate the translation depending on the angle like so:
x = p.X - start.X
y = p.Y - start.Y
Select Case angulo
Case 0
m.Translate(x, y)
Case 90
m.Translate(-y, x)
Case 180
m.Translate(-x, -y)
Case 270
m.Translate(y, -x)
End Select
Related
I have a WPF TextBlock. I am controlling the font size by using ManipulationDelta, to simulate zooming in/out. It's currently in a very crude way, but it works.
This works for a touchscreen, but I want the same behaviour to work on my laptop touchpad - i.e. two-finger pinch-zoom.
What's the event I need to hook into to make this work?
The touch code is as follows:
<TextBlock Name="txbl_displaySong" Foreground="White" FontFamily="Lucida Console"
FontSize="22" Text="{Binding Path=T.SelectedSong.TransposedChordsOverLyrics, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Padding="20" TextWrapping="Wrap" IsManipulationEnabled="True"
ManipulationDelta="txbl_displaySong_ManipulationDelta"
ManipulationCompleted="Txbl_displaySong_ManipulationCompleted"
TouchDown="Txbl_displaySong_TouchDown"
MouseDown="Txbl_displaySong_MouseDown"/>
Code Behind:
Dim isPinchIn As Boolean = False
Dim isPinchOut As Boolean = False
Dim prevScale As Double = 0
Private Sub Txbl_displaySong_ManipulationCompleted(sender As Object, e As ManipulationCompletedEventArgs)
prevScale = 0
isPinchIn = False
isPinchOut = False
End Sub
Private Sub txbl_displaySong_ManipulationDelta(sender As Object, e As ManipulationDeltaEventArgs)
Dim tScale As Double = e.CumulativeManipulation.Scale.Length
If (prevScale > 0) Then
isPinchIn = isPinchIn OrElse prevScale > tScale ' if same scale, assume no change
isPinchOut = isPinchOut OrElse prevScale < tScale ' if same scale, assume no change
End If
prevScale = tScale
Dim mCount As Integer = e.Manipulators.Count
...
If mCount = 2 Then
If isPinchIn Then
txbl_displaySong.FontSize = Math.Max(6.0, txbl_displaySong.FontSize - 0.2) ' limit to 6
ElseIf isPinchOut Then
txbl_displaySong.FontSize = Math.Min(40.0, txbl_displaySong.FontSize + 0.2) ' limit to 40
Else
End If
End If
End Sub
...
I have the same problem, and I figured out a workaround which half solves it:
Wire up some code to the MouseWheel event:
private void Canvas_MouseWheel(object sender, MouseWheelEventArgs e)
{
if (e.Delta > 0)
...
else if (e.Delta < 0)
...
}
With my touchpad, I get a Delta of either 120 or -120 depending on whether I'm pinching to zoom in or pinching to zoom out.
I'm working on project where the user will enter a JobNumber, say (J000001), and when the user hits print the jobnumber will print. With the code below, I'm able to print the numbers, say (001), but I want the user to enter the actual JobNumber (J000001). Any help on this is greatly appreciated.
When I enter the JobNumber (J000001), I get the following error message:
'Invalid CastException was unhandled'
Conversion from string "J000001" to type boolean is not valid.
Below is my VB Code:
Imports System.Globalization
Imports System.Drawing.Printing
Imports System.Drawing
Class MainWindow
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
AddHandler printDocument1.PrintPage, AddressOf printDocument1_PrintPage
End Sub
'Declaration the global variables
Private paperSize As New PaperSize("papersize", 300, 500)
'set the paper size
Private totalnumber As Integer = 0
'this is for total number of items of the list or array
Private itemperpage As Integer = 0
'this is for no of item per page
Private printDocument1 As New PrintDocument()
Private printDialog1 As New System.Windows.Forms.PrintDialog()
Private DefaultFont As New Font("Calibri", 20)
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
If txtStart.Text Then
itemperpage = 1
totalnumber = txtStart.Text
printDialog1.Document = printDocument1
printDocument1.DefaultPageSettings.PaperSize = paperSize
printDialog1.ShowDialog()
'printDocument1.PrinterSettings.PrinterName = "";
printDocument1.Print()
Else
MessageBox.Show("Invalid number")
End If
End Sub
Private Function CheckNumber(str As String)
Dim Num As Double
Return Double.TryParse(str, Num)
End Function
'Define the Printpage event of the printdocument
Private Sub printDocument1_PrintPage(sender As Object, e As System.Drawing.Printing.PrintPageEventArgs)
Dim currentY As Single = 10
While totalnumber <= CInt(txtStart.Text)
' check the number of items
e.Graphics.DrawString(totalnumber.ToString(), DefaultFont, System.Drawing.Brushes.Black, 50, currentY)
'print each item
currentY += 20
' set a gap between every item
totalnumber += 1
'increment count by 1
If itemperpage < 1 Then
' check whether the number of item(per page) is more than 1 or not
itemperpage += 1
' increment itemperpage by 1
' set the HasMorePages property to false , so that no other page will not be added
e.HasMorePages = False
Else
' if the number of item(per page) is more than 1 then add one page
itemperpage = 1
'initiate itemperpage to 0 .
If totalnumber <= Convert.ToInt32(txtStart.Text) Then
e.HasMorePages = True
End If
'e.HasMorePages raised the PrintPage event once per page .
'It will call PrintPage event again
Return
End If
End While
End Sub
End Class
XAML code
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="175" Width="303">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="1.5*" />
</Grid.ColumnDefinitions>
<Label Content="Start Number:" />
<TextBox x:Name="txtStart" Grid.Column="1" />
<Button Grid.Row="2" Grid.ColumnSpan="2" Content="Print" Click="Button_Click" />
</Grid>
</Window>
The issue is your If statement in the Button_Click method.
If txtStart.Text Then
The If takes a boolean, but you are passing it a string. VB.Net is trying to convert the string to a boolean. 001 works, because it can convert that. J000001 is not able to be converted to a boolean.
Do you mean to check if there is a value entered?
If !String.IsNullOrWhiteSpace(txtStart.Text) Then
You will also run into a similar issue when assigning the value to totalnumber.
You are comparing the value of the text box as a boolean, and then assigning the value of your Text Box to a variable of type Integer.
If txtStart.Text Then
should probably be something like:
If !String.IsNullOrEmpty(txtStart.Text) Then
And then if you job numbers are alpha numeric, use a variable of type String instead of Integer.
I have a canvas that shows an audio waveform, which is made using a lot of Lines. Each line is Tagged with it's time code so I can identify where in the audio it is.
I want to put a rectangle on the canvas based on data stored in an observable collection.
Basically, Timespan start and end points so I can show a block of audio.
The problem I'm having is that to show the rectangle, I have to know the Canvas left value and width.
I can get these by scanning through the canvas children until I find the correct line and getting its X1 value, but I don't know how to do it in a binding.
I want to bind the observable collection ItemsControl so I can show the rectangles on the canvas.
Is it possible to bind to a function or something that would do the calculations based on the data in the observable collection?
XAML:
<ScrollViewer Grid.Row="2" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Hidden">
<Canvas Name="waveform" >
<ItemsControl Name="RectArea"> <!-- Where I hope to have the rectangles appear on top of the waveform canvas -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Stroke="Yellow" Fill="Yellow" Opacity="0.2" Height="200" Width="{Binding Width}" Canvas.Left="{Binding Left}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Canvas>
</ScrollViewer>
Creating the waveform:
Dim seconds As Integer = 0
lines = New Dictionary(Of String, Line)
Using Reader As New AudioFileReader(openfile.FileName)
Dim samples = Reader.Length / (Reader.WaveFormat.Channels * Reader.WaveFormat.BitsPerSample / 8)
Dim f = 0.0F
Dim max = 0.0F
Dim batch As Integer = Math.Max(10, samples / samplecount)
Dim mid = 100
Dim yScale = 100
Dim buffer(batch) As Single
Dim read As Integer
Dim xPos = 0
read = Reader.Read(buffer, 0, batch)
While read = batch
For n As Integer = 0 To read
max = Math.Max(Math.Abs(buffer(n)), max)
Next
Dim line As New Line
line.X1 = xPos
line.X2 = xPos
line.Y1 = mid + (max * yScale)
line.Y2 = mid - (max * yScale)
line.Tag = Reader.CurrentTime
line.StrokeThickness = 1
line.Stroke = Brushes.DarkGray
AddHandler line.MouseDown, AddressOf Line_MouseDown
waveform.Children.Add(line)
' lines is a dictionary that holds all of the line information. nothing is bound to it, it just allows me to search against time code so I can highlight the line as the audio is playing'
If Not lines.ContainsKey(Reader.CurrentTime.Hours.ToString().PadLeft(2, "0") & Reader.CurrentTime.Minutes.ToString().PadLeft(2, "0") & Reader.CurrentTime.Seconds.ToString().PadLeft(2, "0") & Reader.CurrentTime.Milliseconds.ToString().PadLeft(3, "0").Substring(0, 1)) Then
lines.Add(Reader.CurrentTime.Hours.ToString().PadLeft(2, "0") & Reader.CurrentTime.Minutes.ToString().PadLeft(2, "0") & Reader.CurrentTime.Seconds.ToString().PadLeft(2, "0") & Reader.CurrentTime.Milliseconds.ToString().PadLeft(3, "0").Substring(0, 1), line)
End If
' Draw a tall black line and show timecode every 10 seconds to make it easier to see where you are on the code '
If Reader.CurrentTime.TotalSeconds > (seconds + 10) Then
seconds = Reader.CurrentTime.TotalSeconds
line = New Line
line.X1 = xPos
line.X2 = xPos
line.Y1 = mid + yScale
line.Y2 = mid - yScale
line.StrokeThickness = 1
line.Stroke = Brushes.Black
waveform.Children.Add(line)
Dim textblock As New TextBlock
textblock.Text = Reader.CurrentTime.Hours.ToString().PadLeft(2, "0") & ":" & Reader.CurrentTime.Minutes.ToString().PadLeft(2, "0") & ":" & Reader.CurrentTime.Seconds.ToString().PadLeft(2, "0") & "," & Reader.CurrentTime.Milliseconds.ToString().PadLeft(3, "0")
textblock.Foreground = Brushes.Black
Canvas.SetLeft(textblock, xPos)
Canvas.SetTop(textblock, yScale)
waveform.Children.Add(textblock)
End If
max = 0
xPos += 1
read = Reader.Read(buffer, 0, batch)
End While
waveform.Width = xPos
End Using
ObservableCollection:
Imports System.ComponentModel
Imports System.Collections.ObjectModel
Public Class ocAudioSelection
Implements INotifyPropertyChanged
Private _Changed As Boolean
Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
Protected Overridable Sub OnPropertyChanged(ByVal Propertyname As String)
On Error GoTo sError
If Not Propertyname.Contains("Changed") Then
Changed = True
End If
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(Propertyname))
Exit Sub
sError:
MsgBox(ErrorToString)
End Sub
Public Property Changed() As Boolean
Get
Return _Changed
End Get
Set(ByVal value As Boolean)
If _Changed <> value Then
_Changed = value
OnPropertyChanged("Changed")
End If
End Set
End Property
Private _startTime As String
Private _endTime As String
Public Sub New()
End Sub
Public Sub New(startTime As String)
_startTime = startTime
End Sub
Public Sub New(startTime As String, endTime As String)
_startTime = startTime
_endTime = endTime
End Sub
Public Property StartTime As String
Get
Return _startTime
End Get
Set(value As String)
If value <> _startTime Then
_startTime = value
OnPropertyChanged("StartTime")
End If
End Set
End Property
Public Property EndTime As String
Get
Return _endTime
End Get
Set(value As String)
If value <> _endTime Then
_endTime = value 'TimeSpan.Parse()
OnPropertyChanged("EndTime")
End If
End Set
End Property
End Class
I am creating my own NumericUpDown control in VB. Here is my XAML:
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
x:Class="NumericUpDown"
mc:Ignorable="d"
d:DesignHeight="30" d:DesignWidth="100">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="20" />
<ColumnDefinition Width="20" />
</Grid.ColumnDefinitions>
<TextBox x:Name="txtNum" Grid.Column="0" x:FieldModifier="private" TextChanged="txtNum_TextChanged"/>
<Button x:Name="cmdDown" Grid.Column="1" x:FieldModifier="private" Content="˅" Width="20" Click="cmdDown_Click" />
<Button x:Name="cmdUp" Grid.Column="2" x:FieldModifier="private" Content="˄" Width="20" Click="cmdUp_Click" />
</Grid>
</UserControl>
And here is the VB code behind it:
Class NumericUpDown
Dim _Minimum As Double = 0
Dim _Maximum As Double = 100
Private Sub NumericUpDown()
InitializeComponent()
txtNum.Text = Numeric
End Sub
Public Property Maximum As Double
Get
Return _Maximum
End Get
Set(value As Double)
_Maximum = value
End Set
End Property
Public Property Minimum As Double
Get
Return _Minimum
End Get
Set(value As Double)
_Minimum = value
End Set
End Property
Public Shared ReadOnly NumericProperty As DependencyProperty = DependencyProperty.Register("Numeric", GetType(String), GetType(NumericUpDown), _
New PropertyMetadata(""))
Public Property Numeric As String
Get
Return CType(GetValue(NumericProperty), String)
End Get
Set(value As String)
SetValue(NumericProperty, value)
End Set
End Property
Private Sub cmdUp_Click(sender As Object, e As RoutedEventArgs)
Dim NumValue As Double
NumValue = Val(txtNum.Text)
NumValue += 1
If NumValue > Maximum Then NumValue = Maximum
txtNum.Text = NumValue.ToString
End Sub
Private Sub cmdDown_Click(sender As Object, e As RoutedEventArgs)
Dim NumValue As Double
NumValue = Val(txtNum.Text)
NumValue -= 1
If NumValue < Minimum Then NumValue = Minimum
txtNum.Text = NumValue.ToString
End Sub
Private Sub txtNum_TextChanged(sender As Object, e As TextChangedEventArgs)
Numeric = txtNum.Text
End Sub
End Class
I use it in my page like this:
Put this on page definition:
xmlns:local="clr-namespace:Demo"
And put this in the content section:
<local:NumericUpDown Numeric="{Binding Path=score, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}"/>
Of course I have already set DataContext on the container and all other databound controls work as they should. But the textbox in my custom control turned out empty! It doesn't end here. When I type something in the textbox and when I give it some value using decrease and increase button, the value is transferred to my DataTable; which means this usercontrol does work to some extend. Where did I do wrong? Why won't the Textbox content be initialized with the starting value?
After a little more testing. It seems that my usercontrol doesn't work in 'Two-Way'. It doesn't receive data from DataTable, it only propagates value to it. How do I fix it?
The issue is that you are not binding the Text property of txtNum to your Numeric property.
<TextBox x:Name="txtNum" Grid.Column="0" x:FieldModifier="private"
Text="{Binding Path=Numeric, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"/>
Then you can remove txtNum_TextChanged, and modify your up/down click handlers to just update the Numeric property, e.g.:
Private Sub cmdUp_Click(sender As Object, e As RoutedEventArgs)
If Me.Numeric < Me.Maximum Then
Me.Numeric += 1
Else
Me.Numeric = Me.Maximum
End If
End Sub
Private Sub cmdDown_Click(sender As Object, e As RoutedEventArgs)
If Me.Numeric > Me.Minimum Then
Me.Numeric -= 1
Else
Me.Numeric = Me.Minimum
End If
End Sub
Note that there are still lots of issues - a user can enter a value outside of the allowed range, or non-numeric data (which will break things!), etc. For this specific problem, you could check out the Extended EPF Toolkit, which has various up/down controls.
I've been hunting through stackoverflow for a while to answer this.
I've got a Listview who's items are Listviews whose children are actually a list(of string) that is a member of the parent listviewitem.
Drag and drop functionality is the goal. However this is proving hard for a variety of reasons, one of which is casting. I need to get the type before I do a direct cast to make it work - at least I think that will get me over one problem.
However I can't get this syntax to even begin to work, so I'll start here:
Dim itemType = listView.ItemContainerGenerator.ItemFromContainer(listViewItem)
Dim g As Type = GetType(itemtype)
This is the entire drag n drop implementation I'm trying:
Dim startpoint As Point
Public Sub List_PreviewMouseLeftButtonDown(sender As Object, e As MouseEventArgs)
' Store the mouse position
startpoint = e.GetPosition(Nothing)
End Sub
Private Sub List_MouseMove(sender As Object, e As MouseEventArgs)
Dim mousePos As Point = e.GetPosition(Nothing)
Dim diff As Vector = startpoint - mousePos
If e.LeftButton = MouseButtonState.Pressed And Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance Or Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance Then
Dim listView As ListView = DirectCast(sender, ListView)
Dim listViewItem As ListViewItem = FindAncestor(Of ListViewItem)(DirectCast(e.OriginalSource, DependencyObject))
Dim itemType = listView.ItemContainerGenerator.ItemFromContainer(listViewItem)
Dim g As Type = GetType(itemtype)
Dim item As String = DirectCast(listView.ItemContainerGenerator.ItemFromContainer(listViewItem), String)
Dim dragData As New DataObject("myFormat", item)
DragDrop.DoDragDrop(listViewItem, dragData, DragDropEffects.Move)
End If
End Sub
Private Shared Function FindAncestor(Of T As DependencyObject)(current As DependencyObject) As T
Do
If TypeOf current Is T Then
Return DirectCast(current, T)
End If
current = VisualTreeHelper.GetParent(current)
Loop While current IsNot Nothing
Return Nothing
End Function
Private Sub DropList_DragEnter(sender As Object, e As DragEventArgs)
If Not e.Data.GetDataPresent("myFormat") OrElse sender = e.Source Then
e.Effects = DragDropEffects.None
End If
End Sub
Private Sub DropList_Drop(sender As Object, e As DragEventArgs)
If e.Data.GetDataPresent("myFormat") Then
Dim contact As String = TryCast(e.Data.GetData("myFormat"), String)
Dim listView As ListView = TryCast(sender, ListView)
listView.Items.Add(contact)
End If
End Sub
Here is the nested listView:
<!--DataContext="{StaticResource RcpdInsertViewSource}" This is a collectionviewsource.
RCPDInsert has a list(of string) member that is created from a single string property
and whose order needs to be alterable.
Eg rcpdInsert.template="[stuff] [more stuff]" so rcpdInsert.templateList = list(of String) from template.split("] [") -->
<ListView Grid.Column="1" Grid.Row="1" ItemsSource="{Binding}"
PreviewMouseLeftButtonDown="List_PreviewMouseLeftButtonDown"
PreviewMouseMove="List_MouseMove"
Drop="DropList_Drop"
DragEnter="DropList_DragEnter"
AllowDrop="True">
<ListView.ItemTemplate>
<DataTemplate>
<DockPanel>
<TextBox Text="{Binding Path=cpID}"></TextBox>
<TextBox Text="{Binding Path=fieldRef}"></TextBox>
<ListView ItemsSource="{Binding Path=InsertsList}" >
<ListView.ItemTemplate>
<DataTemplate DataType="DataClasses1:RcpdInsert.template" >
<StackPanel Orientation="Horizontal" Grid.Row="0">
<TextBlock Text="{Binding}" Margin="5" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DockPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Goal: Drag and drop reordering of child listviews, ideally being able to pull individual items from one child listView to another. When saved, the code behind will actually concat the strings back together and update the template member.
For context here are the relevant members of RcpdInsert:
Sub SetupInsertList()
_insertsList = template.Split(" ").ToList()
For Each item In InsertsList
Dim t = item
RcpdList.Add(RcpdSet.RpcdListShared.Where(Function(x) x.insertID = t).ToList())
Next
End Sub
Public Property RcpdList As New List(Of List(Of Rcpd))
Private Property _insertsList As New List(Of String)
Public Property InsertsList As List(Of String)
Get
If _insertsList.Count = 0 Then setupInsertList()
Return _insertsList
End Get
Set(value As List(Of String))
Dim combine As String = value.Aggregate("", Function(current, i) current + (i & " "))
template = combine
End Set
End Property
The casting is one issue with this, I'm hoping being able to do this part means that the others will be easier to resolve.
Thanks in advance to anyone who can help :)