|
Jippi, I get to answer my own question. The problem is that you have to force it to remember the last position.
<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="350" Width="525">
<Grid>
<Image Name="Image" Source="TwitterBirdsAttack.jpg" MouseMove="Image_MouseMove" MouseUp="Rectangle_MouseLeftButtonUp" />
<Rectangle Name="Rect" Width="100" Height="100" Fill="Transparent" Stroke="Red" StrokeThickness="5" MouseLeftButtonDown="Rectangle_MouseLeftButtonDown" MouseLeftButtonUp="Rectangle_MouseLeftButtonUp">
<Rectangle.RenderTransform>
<TranslateTransform x:Name="trs" X="0" Y="0"/>
</Rectangle.RenderTransform>
</Rectangle>
</Grid>
</Window>
The code behind:
Class MainWindow
Private moveRect As Boolean
Private trans As TranslateTransform = Nothing
Private originalMousePosition As Point
Private LastPos As New Point
Private Sub Rectangle_MouseLeftButtonDown(sender As Object, e As MouseButtonEventArgs)
originalMousePosition = e.GetPosition(Image)
moveRect = True
Rect.IsHitTestVisible = False
End Sub
Private Sub Image_MouseMove(sender As Object, e As MouseEventArgs)
If moveRect Then
If LastPos <> Nothing Then
trs.Y = -(originalMousePosition.Y - e.GetPosition(Image).Y - LastPos.Y)
trs.X = -(originalMousePosition.X - e.GetPosition(Image).X - LastPos.X)
Else
trs.Y = -(originalMousePosition.Y - e.GetPosition(Image).Y)
trs.X = -(originalMousePosition.X - e.GetPosition(Image).X)
End If
End If
End Sub
Private Sub Rectangle_MouseLeftButtonUp(sender As Object, e As MouseButtonEventArgs)
moveRect = False
Rect.IsHitTestVisible = True
LastPos.X = trs.X
LastPos.Y = trs.Y
End Sub
End Class
|
|
|
|
|
hi
in part of my WPF Application I need something like a day of calendar that has from up 00:00 to down 23:59 and I need to drag and drop the songs on it to get play in specific time. like a play list.
that's in my mind and I need to know how can I create that calendar day.
what kind of controls should I use? is there some code sample to help me to get some idea?
thanks
|
|
|
|
|
Rather than use a calendar control, which is a rather heavy duty object with lots of stuff around appointments etc, I would use a listbox or a treelistview which are much simpler collection controls.
I presume you do not need the appointment functionality.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Hi,
Please suggest me any way to achieve this functionality. I have one textbox1, when I enter any value to this textbox1 then it should update to other textboxes i.e. textbox2, textbox3, textbox4, textbox5.....
|
|
|
|
|
You need to use the ElementName property of the Binding :
Binding.ElementName Property[^]
WPF Data Binding - Part 1[^]
<StackPanel>
<TextBox Name="textBox1" />
<TextBox Name="textBox2" Text="{Binding ElementName=textBox1, Path=Text}" />
<TextBox Name="textBox3" Text="{Binding ElementName=textBox1, Path=Text}" />
<TextBox Name="textBox4" Text="{Binding ElementName=textBox1, Path=Text}" />
<TextBox Name="textBox5" Text="{Binding ElementName=textBox1, Path=Text}" />
</StackPanel>
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thanks Richard...
|
|
|
|
|
Hi,
I'm using SharpDX for DirectInput joystick management...and I can't resolve the problem I get while setting cooperative level
Imports SharpDX
Imports SharpDX.DirectInput
Imports System.Windows.Interop
Class MainWindow
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
MainForJoystick()
End Sub
Private Shared Sub MainForJoystick()
Dim directInput As New DirectInput
Dim joystickGuid = Guid.Empty
For Each deviceInstance As DeviceInstance In directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)
joystickGuid = deviceInstance.InstanceGuid
Next
If joystickGuid = Guid.Empty Then
For Each deviceInstance As DeviceInstance In directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)
joystickGuid = deviceInstance.InstanceGuid
Next
End If
If joystickGuid = Guid.Empty Then
Debug.Print("No joystick/Gamepad found.")
End If
Dim hwnd As IntPtr = New WindowInteropHelper(Application.Current.MainWindow).EnsureHandle()
Dim joystick = New Joystick(directInput, joystickGuid)
joystick.SetCooperativeLevel(hwnd, CooperativeLevel.Foreground)
Debug.Print("Found Joystick/Gamepad with GUID: {0}", joystickGuid)
joystick.Properties.BufferSize = 128
joystick.Acquire()
While True
joystick.Poll()
Dim datas = joystick.GetBufferedData()
For Each state As JoystickUpdate In datas
Debug.Print(state.ToString)
If state.Offset = 60 Then
If state.Value = 128 Then
Debug.Print("Up button pressed")
End If
End If
Next
End While
End Sub
End Class
The problem comes from here:
joystick.SetCooperativeLevel(hwnd, CooperativeLevel.Foreground)
SharpDX.SharpDXException was unhandled
HResult=-2147024809
Message=HRESULT: [0x80070057], Module: [SharpDX.DirectInput], ApiCode: [DIERR_INVALIDPARAM/InvalidParam], Message: Incorrect parameter.
Please would you please help me understand what I'm doing wrong? I've been searching for days to resolve this!!
Many thanks!
modified 23-Jan-15 12:18pm.
|
|
|
|
|
I have a very strange issue that I have been unable to resolve. I have a window that is opened on a new thread that contains a custom control box with the min, max, and close buttons as ellipses, with handlers attached:
<StackPanel DockPanel.Dock="Right" Name="ControlBox" Orientation="Horizontal" HorizontalAlignment="Right" Height="22" VerticalAlignment="Center" Margin="0,4,0,0" Background="LightGray" >
<Ellipse Margin="5,0,5,0" VerticalAlignment="Top" HorizontalAlignment="Right"
Width="14" Height="15" MouseLeftButtonUp="btnMinimize_MouseLeftButtonUp"
MouseEnter="ActivateTitleIcons" MouseLeave="DeactivateTitleIcons"
MouseLeftButtonDown="btnMinimize_MouseLeftButtonDown" Name="btnMinimize"
Fill="{StaticResource Min_inact}" Visibility="{Binding Path=MinimizeButtonVisible, Converter={StaticResource ResourceKey=BooleanVisibilityConverter}}"/>
<Ellipse Margin="0,0,5,0" VerticalAlignment="Top" HorizontalAlignment="Right"
Width="14" Height="15" MouseLeftButtonUp="btnMaximize_MouseLeftButtonUp"
MouseEnter="ActivateTitleIcons" MouseLeave="DeActivateTitleIcons"
MouseLeftButtonDown="btnMaximize_MouseLeftButtonDown" Name="btnMaximize"
Fill="{DynamicResource Max_inact}" Visibility="{Binding Path=MaximizeButtonVisible, Converter={StaticResource ResourceKey=BooleanVisibilityConverter}}"/>
<Ellipse Margin="0,0,5,5" VerticalAlignment="Top" HorizontalAlignment="Right"
Width="14" Height="15" MouseLeftButtonUp="btnClose_MouseLeftButtonUp"
MouseEnter="ActivateTitleIcons" MouseLeave="DeActivateTitleIcons"
MouseLeftButtonDown="btnClose_MouseLeftButtonDown" Name="btnClose"
Fill="{DynamicResource Close_inact}" Visibility="{Binding Path=CloseButtonVisible, Converter={StaticResource ResourceKey=BooleanVisibilityConverter}}"/>
</StackPanel>
As an example of the problem, here is the code for the minimize button's MouseLeftButtonDown and MouseLeftButtonUp handlers:
Private Sub btnMinimize_MouseLeftButtonDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
btnMinimize.Fill = CType(Me.Resources("Min_pr"), ImageBrush)
End Sub
Private Sub btnMinimize_MouseLeftButtonUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
btnMinimize.Fill = CType(Me.Resources("Min_inact"), ImageBrush)
SystemCommands.MinimizeWindow(_parent)
End Sub
Now if I just run the application, when I click the minimize button it changes to the proper image but when I let go of the mouse button nothing happens; the window doesn't minimize. Same thing if I set break points anywhere in the btnMinimize_MouseLeftButtonUp method, however if I set a break point on the Private Sub btnMinimize_MouseLeftButtonDown ... line, then the window minimize as it should.
I have never come across this. How does the btnMinimize_MouseLeftButtonUp method run only if I set a break point on the Private Sub btnMinimize_MouseLeftButtonDown ... line? Any suggestions on how this can be resolves is greatly appreciated.
Thank You
A black hole is where God tried to divide by zero.
There are 10 kinds of people in the world; those who understand binary and those who don't.
|
|
|
|
|
All GUI stuff needs to be done on the main thread. Other threads are for work only.
|
|
|
|
|
I believe that when you set a breakpoint on this point it still doesn't work. The only change that you're feeling to be the Minimize effect, is actually the IDE taking over as Active Window (minimizing other Windows) when your code hits the point of the breakpoint.
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
Just using the stock example from Microsoft:
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
IntPtr mainWindowPtr = new WindowInteropHelper(this).Handle;
HwndSource mainWindowSrc = HwndSource.FromHwnd(mainWindowPtr);
mainWindowSrc.CompositionTarget.BackgroundColor = Color.FromArgb(0, 0, 0, 0);
System.Drawing.Graphics desktop = System.Drawing.Graphics.FromHwnd(mainWindowPtr);
float DesktopDpiX = desktop.DpiX;
float DesktopDpiY = desktop.DpiY;
MARGINS margins = new MARGINS();
margins.cxLeftWidth = Convert.ToInt32(5 * (DesktopDpiX / 96));
margins.cxRightWidth = Convert.ToInt32(5 * (DesktopDpiX / 96));
margins.cyTopHeight = Convert.ToInt32(((int)90) * (DesktopDpiX / 96));
margins.cyBottomHeight = Convert.ToInt32(5 * (DesktopDpiX / 96));
int hr = DwmExtendFrameIntoClientArea(mainWindowSrc.Handle, ref margins);
if (hr < 0)
{
}
}
On my machine, I get a white rectangle over the entire window for about 1 second and then the window redraws properly.
This code works on .NET 4.5.1, but this seems to have cropped up in .NET 4.5.2.
|
|
|
|
|
Try calling the code from the window's SourceInitialized event[^], which should fire earlier than the Loaded event.
You might also need to call DwmEnableBlurBehindWindow to reset the blur effect for the window.
Here's the code I use: https://gist.github.com/RichardD2/ef4ee339ce3dcc10264b[^]
That lets you enable the glass effect and set up the thickness using two attached properties. There's an additional real-only attached property which indicates whether the glass effect has been applied, which you can use to adapt your styles where necessary.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Tried moving it to SourceInitialized and get the same result. 4.5.1 works perfectly and 4.5.2 has the 1 - 2 second start up lag. This isn't even a question of framework targeting, just if you have > 4.5.1 installed on the machine, it happens.
|
|
|
|
|
I have been writing C# Winform applications for years but would Like to make the move to wpf applications.
I feel I have gotten all I can out of YouTube tutorials on the subject and have a basic understanding but I feel if I had to do anything at all complex I wouldn't know how to do it correctly and resort to putting everything into the code-behind and start treating it as more of a winform application.
The only place I have found that explicitly lists wpf tutorial videos is http://www.learnvisualstudio.net/ and that appears to only have about two hours of video on the subject.
Ideally I would love to find somewhere that had 10-20 videos that build more and more complex applications that demonstrate the different features within wpf. Is there anything like this? Is a book such as this: WPF 4.5 Unleashed the best way to learn?
Additionally, I would like to learn the MVVM architecture for use in wpf. I would also appreciate any suggestion on that subject too.
modified 5-Jan-15 15:21pm.
|
|
|
|
|
I've never found any tutorials I would consider "100% correct".
Just a tip: Forget Winforms. WPF code written in "Winforms style" is a disaster unless its a quick throw away app. Start with MVVM from Day 1.
Also, you can't do MVVM with .NET "out of the box". You'll need an MVVM framework. There are lots of open source frameworks out there.
If you *REALLY* want to learn WPF / MVVM at an expert level, I'd suggest writing your own MVVM framework as a learning process and having it be your "bag of tricks" that you take with you from job to job. Its not that hard. You pretty start off with a ViewModelBase class and toss in a good old RelayCommand implementation and your pretty much there. You'd also need a messenger service.
DI should definitely be a part of your MVVM toolkit, takes care of a lot of the work.
You may not know any of these terms LOL, but if you research those keywords a little bit, you'll start to get how a proper MVVM application is put together.
|
|
|
|
|
I agree with Sludge, work through some of the MVVM tutorials, we use the Galasoft MVVM light framework which is popular and light weight.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
|
Oops, was thinking that as a joke, it must have gone out the finger, I suppose I should take the advice and read carefully my responses.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
|
|
|
I am working on an application that will need to open multiple windows, each on a separate thread. I have each on a different thread because each window represents a "Ticket" which will need to get data from a server, update a server, as well as other stuff and when all were running on a single thread some of the ticket windows were lagging.
I am able to create the ticket windows and pass arguments, however as soon as I start trying to update properties on the window I get exceptions. Currently each window that needs to be created is created using this method:
Private Shared Sub CreateNewWindow(Of T As Window)(ByVal newThread As Boolean, ByVal onOpened As Action(Of T), ByVal ParamArray args() As Object)
Dim activateWindow As Action = Sub()
Dim window As T = DirectCast(Activator.CreateInstance(GetType(T), args), T)
AddHandler window.Closed, Sub(s, e)
window.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Background)
End Sub
window.Show()
If onOpened IsNot Nothing Then
onOpened(window)
End If
End Sub
If newThread Then
Dim newWindowThread As New Thread(New ThreadStart(Sub()
SynchronizationContext.SetSynchronizationContext(New DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher))
activateWindow()
System.Windows.Threading.Dispatcher.Run()
End Sub))
newWindowThread.SetApartmentState(ApartmentState.STA)
newWindowThread.IsBackground = True
newWindowThread.Start()
Else
activateWindow()
End If
End Sub
And the window's constructor is:
Public Sub New(properties As WindowProperties)
InitializeComponent()
_ticket = properties.Ticket
Me.Top = properties.Top
SetupWindow()
End Sub
And the SetupWindow method is:
Private Sub SetupWindow()
Try
TitleBarColor = currentSettings.DefaultTicketBrush
_stop = New ManualResetEvent(False)
Me.Name = "TicketWindow_" & Ticket.id
Me.RegisterName(Me.Name, Me)
If currentSettings.FadeInTicketWindow Then
Dim fadeInAnimation As New DoubleAnimation
With fadeInAnimation
.From = 0.0
.To = 1.0
.Duration = New Duration(TimeSpan.FromSeconds(0.75))
.AutoReverse = False
End With
fadeInStoryboard = New Storyboard
fadeInStoryboard.Children.Add(fadeInAnimation)
Storyboard.SetTargetName(fadeInAnimation, Me.Name)
Storyboard.SetTargetProperty(fadeInAnimation, New PropertyPath(Window.OpacityProperty))
fadeInStoryboard.Begin(Me)
End If
Catch ex As Exception
Dim m As String = ex.Message
End Try
End Sub
Where currentSettings is an global object which is an instance of a AppSettings object which contains some configuration data andTitleBarColor is a property of the window (which implements INotifyPropertyChanged ) used for binding:
Public Property TitleBarColor As Brush
Get
Return _titleBarColor
End Get
Private Set(value As Brush)
Try
_titleBarColor = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("TitleBarColor"))
Catch ex As Exception
Dim m As String = ex.Message
End Try
End Set
End Property
However with the code this way I get an exception in the CreateWindow method at window.show which says "Must create DependencySource on same Thread as the DependencyObject".
However If I change the TitleBarColor properties Set method to:
LTitleBar.Dispatcher.Invoke(New Action(Sub()
LTitleBar.Fill = value
End Sub))
Then the exception is caught in the property with the message "The calling thread cannot access this object because a different thread owns it."
I would appreciate any assistance in how I can update properties of a window which is on a separate thread but needs to access objects on a different thread (e.g. currentSettings ) and still have binding working. I have tried various pieces of code I have found on the web but none of them have worked for me. There was one piece of code that seems to work (no exception thrown) but the bound properties did not update when a change was made to the TitleBarColor property.
Thank you in advance for any assistance with this.
A black hole is where God tried to divide by zero.
There are 10 kinds of people in the world; those who understand binary and those who don't.
|
|
|
|
|
I am unsure whether the problem was generated from these objects, or from any other underlying objects inside your code. I remember, I once had the same problem and the Dispatcher worked for me.
But I would like to advise, that the second exception is raised when there was a resource being used and another thread attempts to use it too. In that case, it throws this exception. So, a tip might be give to you, you must always try to use the Dispose() method to dispose all of the resources and release them before closing your applications. This would minimize the second exceptions.
Or even if you don't remember calling this method on every dispose-able object. Them you might consider using such objects under a using block. Which will let the .NET take care of these resources once you're done working with them.
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
As discussed in your other thread, all GUI work needs to be done on the main thread. You need to restructure your code so that the *work* for each window is done in a background thread (easy with the async keyword or TPL for example) so it doesn't block the UI.
Also, bindings should generally be lazy loaded. If they are expensive or time consuming, you should make them async or background.
You will encounter endless hurdles creating GUI objects on background threads.
|
|
|
|
|
I have this enum:
public enum MyEnum
{
[Description("This is enum A")]
EnumA,
[Description("This is enum B")]
EnumB,
[Description("This is enum C")]
EnumC,
}
}
I bound it to a datagrid like this:
<Window.Resources>
<ResourceDictionary>
<ObjectDataProvider x:Key="projectTypeList"
MethodName="GetValues"
ObjectType="{x:Type enums:MyEnum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="enums:MyEnum"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</ResourceDictionary>
</Window.Resources>
and then
<DataGrid Grid.Row="1">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Project Type"
ItemsSource="{Binding Source={StaticResource projectTypeList}}"
Width="150"/>
</DataGrid.Columns>
</DataGrid>
I can see the enum values in the combo. What I'd really like is to show the descriptions. Can someone show me how to do this?
Many thanks!
If it's not broken, fix it until it is
|
|
|
|
|