This question already has answers here:
SurfaceScrollViewer: getting touch on nested children
(2 answers)
Closed 2 years ago.
I have been banging my head on this for a while now! Here is my simple User Control:
<UserControl x:Class="DaCapo.MyUserControl"
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"
xmlns:s="http://schemas.microsoft.com/surface/2008"
IsManipulationEnabled="True"
Width="300" Height="300">
<Canvas>
<s:SurfaceButton x:Name="button" Width="100" Height="100" Content="Click!" Style="{x:Null}"/>
<Popup x:Name="popup" Width="200" Height="100" IsOpen="False" StaysOpen="True" PlacementRectangle="0,0,200,100"
AllowsTransparency="True" Focusable="True">
<DockPanel x:Name="dockpanel" Width="200" Height="100" Background="SteelBlue" Focusable="True"/>
</Popup>
</Canvas>
</UserControl>
I want to be able to detect touches on the DockPanel or in a possible child of it. Here follows the code behind for the same class, with the alternatives I attempted:
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
TouchExtensions.AddHoldGestureHandler(this.button, this.HoldHandler);
/* NONE OF THE FOLLOWING WORKS */
// TouchExtensions.AddTapGestureHandler(this.popup, this.TapHandler);
// this.dockpanel.TouchDown += new System.EventHandler<TouchEventArgs>(popup_TouchDown);
// this.popup.TouchDown += new System.EventHandler<TouchEventArgs>(popup_TouchDown);
// this.popup.ManipulationStarting += new System.EventHandler<ManipulationStartingEventArgs>(popup_ManipulationStarting);
// this.dockpanel.ManipulationStarting += new System.EventHandler<ManipulationStartingEventArgs>(popup_ManipulationStarting);
}
void popup_ManipulationStarting(object sender, ManipulationStartingEventArgs e) { Debug.WriteLine("Tap..."); }
void popup_TouchDown(object sender, TouchEventArgs e) { Debug.WriteLine("Tap..."); }
private void TapHandler(object sender, TouchEventArgs e) { Debug.WriteLine("Tap..."); }
private void HoldHandler(object sender, TouchEventArgs e) { Debug.WriteLine("Holding..."); this.popup.IsOpen = true; }
}
I do believe I am missing something obvious. Can someone please help me? Thanks.
The Button & popup needs to be connected to its click (or touch) handlers defined in the code behind, in XAML itself.
If you want to handle touch events for the dockpanel, How about
adding a button inside the dockpanel with opacity = 0 ??
EDIT :
I can see that you defined a few handlers, but did you add those Handlers to the button?
For example, for a SurfaceButton :
IN XAML :
<s:SurfaceButton Click="OpenButton_Click"/>
Correspondingly connects the function in C# as:
private void OpenButton_Click(object sender, RoutedEventArgs e)
{
// Handle the action for the click here.
}
Under the covers, Popup creates another hwnd to render its content into. This is different from all other WPF controls. You need to register this hwnd with the Surface SDK so it will start sending touch events to it. Use this to do that: http://msdn.microsoft.com/en-us/library/microsoft.surface.presentation.input.touchextensions.enablesurfaceinput.aspx
Related
i have a window that is acting like a Dialog with two buttons and a textbox, so its an input dialog, the problem is when i press the buttons, or close the dialog window in any way the main window that i used to create this dialog will get closed too! (exit code = 0) and another thing is that it will work OK in vs debugging but when i run the app without vs debugging that owner window get closed and in my case that window is the Main app window so the whole application will shutdown! what am i doing wrong?
XAML:
<Window x:Class="Server.Forms.Dialogs.PokeDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Server.Forms.Dialogs"
mc:Ignorable="d"
Title="Poke" MinHeight="120" MinWidth="225"
ResizeMode="CanResizeWithGrip"
SizeToContent="WidthAndHeight"
x:Name="windowPoke"
Loaded="windowPoke_Loaded">
<StackPanel VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Margin="25">
<Label Content="Poke Reason:"
Padding="0"/>
<TextBox x:Name="textboxPokeReason"
Margin="0 5"/>
<DockPanel>
<Button x:Name="btnOk"
Click="btnOk_Click"
IsDefault="True"
Content="OK"
MinWidth="100"
Margin="0 0 5 0"/>
<Button x:Name="btnCancel"
Click="btnCancel_Click"
IsCancel="True"
Content="Cancel"
MinWidth="100"/>
</DockPanel>
</StackPanel>
C#:
public partial class PokeDialog : Window
{
public string PokeReason
{
get { return textboxPokeReason.Text; }
}
public PokeDialog()
{
InitializeComponent();
}
private void windowPoke_Loaded(object sender, RoutedEventArgs e)
{
textboxPokeReason.Focus();
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
}
the way i used dialog:
private void btnPokeClient_Click(object sender, RoutedEventArgs e)
{
var dialog = new PokeDialog();
if (dialog.ShowDialog() == true)
{
MessageBox.Show("TRUE - input text:" + dialog.PokeReason);
}
else MessageBox.Show("FALSE");
}
i can see the messageboxes too, but after closing this message boxes the whole app will get closed
Got a WPF application which has an on hover popup. The popup contains a list of different files which can be opened (e.g. pdf, excel etc)
You can navigate and select a file by double clicking and it opens as you would expect.
But if I now navigate to a different file I can see that the on hover selection isn't now working,
If you now select a different file, the original file is opened again.
I am using a Process.Start and passing the full path to the file to the method.
The application is a fair size so here are some excerpts for a Test application I have written to look into this further
The XAML for the main window
<Window x:Class="TestPopupIssue.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">
<Canvas Margin="5" Background="Red" Width="200" Height="150" >
<Rectangle Name="rectangle1"
Canvas.Top="60" Canvas.Left="50"
Height="85" Width="60"
Fill="Black" MouseEnter="rectangle1_MouseEnter" MouseLeave="rectangle1_MouseLeave" />
<Popup x:Name="PopupWindow" PlacementTarget="{Binding ElementName=rectangle1}" Placement="Top" MouseEnter="rectangle1_MouseEnter" MouseLeave="rectangle1_MouseLeave">
<ListBox MinHeight="50" ItemsSource="{Binding Files}" MouseDoubleClick="FileList_MouseDoubleClick"`enter code here` x:Name="FileList" />
</Popup>
</Canvas>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
FileList f;
public MainWindow()
{
InitializeComponent();
f = new FileList();
f.PopulateFiles();
this.DataContext = f;
}
private void FileList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (FileList.SelectedItem != null)
{
string item = FileList.SelectedItem as string;
if (item != null)
{
System.Diagnostics.Process.Start(item);
}
}
}
private void rectangle1_MouseEnter(object sender, MouseEventArgs e)
{
PopupWindow.IsOpen = true;
}
private void rectangle1_MouseLeave(object sender, MouseEventArgs e)
{
PopupWindow.IsOpen = false;
}
}
And there is a FileList class which just has a generic string list of file paths called
Files
Thanks
I have tested your Sample-Application, when your opening the File with Process.Start your Focus gets stolen by the Application that opens your File.
Somehow the ListBox in the Popup canĀ“t change their SelectedItem when the Window has lost his Focus.
Unfortunately I have not managed to get the focus back on the Window, this.SetFocus() has not worked for me.
Anyway another possible Solution would be to close the Popup when your opening the File.
private void FileList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (FileList.SelectedItem != null)
{
string item = FileList.SelectedItem as string;
if (item != null)
{
System.Diagnostics.Process.Start(item);
PopupWindow.IsOpen = false;
}
}
}
this way the ListBox can update the selectedItem again.
hope this helps!
I'm doing a sample with MVVM and have a problem with commands. I have an Article class (with ID, Name, Price, etc.), an ArticleViewModel that represents the view model, and a user control (ArticleControl) that allows to input the data for the article, with bindings to the properties of the ArticleViewModel. This user control has a biding for a save command.
<UserControl.CommandBindings>
<CommandBinding x:Name="saveCmd"
Command="local:Commands.Save"
CanExecute="CommandBinding_CanExecute"
Executed="CommandBinding_Executed"/>
</UserControl.CommandBindings>
This is how the command is defined:
public class Commands
{
private static RoutedUICommand _save;
public static RoutedUICommand Save
{
get { return _save; }
}
static Commands()
{
InputGestureCollection saveInputs = new InputGestureCollection();
saveInputs.Add(new KeyGesture(Key.S, ModifierKeys.Control, "Ctrl+S"));
_save = new RoutedUICommand(
"Save",
"Save",
typeof(Commands),
saveInputs);
}
}
And the command binding handlers:
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
double baseprice = 0;
double.TryParse(ArticleBasePrice.Text, out baseprice);
e.CanExecute =
!string.IsNullOrEmpty(ArticleID.Text) &&
!string.IsNullOrEmpty(ArticleName.Text) &&
!string.IsNullOrEmpty(ArticleDescription.Text) &&
baseprice > 0;
}
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
ArticleViewModel avm = (ArticleViewModel)DataContext;
if (avm != null && avm.Save())
{
ArticleID.Text = String.Empty;
ArticleName.Text = String.Empty;
ArticleDescription.Text = String.Empty;
ArticleBasePrice.Text = String.Empty;
}
}
Now, I put this user control on a window. When I hit Ctrl+S the command is executed. However, I also put a Save button on that window, next to this user control. When I click it I want to execute the same command (and I don't want to do another command binding in the window where the user control is hosted).
<StackPanel>
<local:ArticleControl x:Name="articleControl" />
<Button Name="btnSave"
Content="Save" Width="100"
HorizontalAlignment="Left"
Command="{???}"/> <!-- what should I put here? -->
</StackPanel>
But I do not know how to refer that saveCmd defined in the user control. I tried different things, some are completely wrong (they throw exception when running the app), some don't have any effect.
Command="{StaticResource saveCmd}"
Command="{StaticResource local:ArticleControl.saveCmd}"
Command="{x:Static local:Commands.Save}"
Any help is appreciated. Thank you.
The reason why the Save button will not cause the commandbindings of your other control to execute is because the Save button is outside the user control and therefore the command system will not look for a commandbinding in that control. The Command execution strategy is a bit like a bubbling event and will start from the focused item (the Button) and go up the visual tree until it finds the CommandBindings.
You can either implement the command binding in the parent control or set the CommandTarget property of the Save button to the user control.
Another approach is to set the FocusManager.IsFocusScope=True on the button or the container of the button. If you do this I suggest you read up on what IsFocusScope does but in a nutshell it will leave the input focus on whatever control has the focus when you press the button, instead of making the button the new input focus. This is generally used for toolbars or menu like structures.
Based on Patrick's suggestions, this is what I did:
Put the command binding in the user control and implemented the handlers in the code-behind as shown in the original message.
Used Command, CommandTarget and FocusManager properties on the button to point to the binding from the user control (ArticleUserControl is the x:Name of the user control).
This is how the XAML for the window looks:
<Window x:Class="MVVMModel.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MVVMModel"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<local:ArticleControl x:Name="articleControl" />
<Button Name="btnSave" Content="Save" Width="100" HorizontalAlignment="Left"
Command="local:Commands.Save"
CommandTarget="{Binding ElementName=ArticleUserControl}"
FocusManager.IsFocusScope="True" />
</StackPanel>
</Window>
I think you just have to move your CommandBinding to a Resource Dictionary, so that it's available outside your UserControl!
Here is what I did to work, though I'm not particularly happy with the solution. If anyone knows a better approach, please do let me know.
I moved the logic for the commands handler in a separate, static class:
static class CommandsCore
{
public static bool Save_CanExecute(ArticleControl ac)
{
double baseprice = 0;
double.TryParse(ac.ArticleBasePrice.Text, out baseprice);
return
!string.IsNullOrEmpty(ac.ArticleID.Text) &&
!string.IsNullOrEmpty(ac.ArticleName.Text) &&
!string.IsNullOrEmpty(ac.ArticleDescription.Text) &&
baseprice > 0;
}
public static void Save_Executed(ArticleControl ac)
{
ArticleViewModel avm = (ArticleViewModel)ac.DataContext;
if (avm != null && avm.Save())
{
ac.ArticleID.Text = String.Empty;
ac.ArticleName.Text = String.Empty;
ac.ArticleDescription.Text = String.Empty;
ac.ArticleBasePrice.Text = String.Empty;
}
}
}
I kept the command binding in the user control as it was
<UserControl.CommandBindings>
<CommandBinding x:Name="saveCmd"
Command="local:Commands.Save"
CanExecute="CommandBinding_CanExecute"
Executed="CommandBinding_Executed"/>
</UserControl.CommandBindings>
But in the handlers I called the two methods I just defined above.
public void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = CommandsCore.Save_CanExecute(this);
}
public void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
CommandsCore.Save_Executed(this);
}
And then I did the same from the window where the control is used.
<Window x:Class="MVVMModel.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MVVMModel"
Title="MainWindow" Height="350" Width="525">
<Window.CommandBindings>
<CommandBinding x:Name="saveCmd"
Command="local:Commands.Save"
CanExecute="CommandBinding_CanExecute"
Executed="CommandBinding_Executed"/>
</Window.CommandBindings>
<StackPanel>
<local:ArticleControl x:Name="articleControl" />
<Button Name="btnSave" Content="Save" Width="100" HorizontalAlignment="Left"
Command="local:Commands.Save"/>
</StackPanel>
</Window>
and the handlers
public void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = CommandsCore.Save_CanExecute(articleControl);
}
public void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
CommandsCore.Save_Executed(articleControl);
}
And this works, the Save button is enabled only when the fields are filled in appropriately and the command is executed correctly when clicking the button.
I need a draggable popup control in wpf and was wondering if any of your guys could help me out..I did see the following post:
Drag WPF Popup control
but that isnt how its supposed to work...? When i click and drag it always resets to a specific point and moreover the commenters said that this is not an efficient approach...?
Does anyone have any alternatives?
Thanks!
We can write a behavior to make any Popup draggable. Here is some sample XAML of a popup associated with a textbox that opens and stays open when the text box is focused:
<Grid>
<StackPanel>
<TextBox x:Name="textBox1" Width="200" Height="20"/>
</StackPanel>
<Popup PlacementTarget="{Binding ElementName=textBox1}" IsOpen="{Binding IsKeyboardFocused, ElementName=textBox1, Mode=OneWay}">
<i:Interaction.Behaviors>
<local:MouseDragPopupBehavior/>
</i:Interaction.Behaviors>
<TextBlock Background="White">
<TextBlock.Text>Sample Popup content.</TextBlock.Text>
</TextBlock>
</Popup>
</Grid>
Here is the behavior that allows us to drag the Popup:
public class MouseDragPopupBehavior : Behavior<Popup>
{
private bool mouseDown;
private Point oldMousePosition;
protected override void OnAttached()
{
AssociatedObject.MouseLeftButtonDown += (s, e) =>
{
mouseDown = true;
oldMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
AssociatedObject.Child.CaptureMouse();
};
AssociatedObject.MouseMove += (s, e) =>
{
if (!mouseDown) return;
var newMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
var offset = newMousePosition - oldMousePosition;
oldMousePosition = newMousePosition;
AssociatedObject.HorizontalOffset += offset.X;
AssociatedObject.VerticalOffset += offset.Y;
};
AssociatedObject.MouseLeftButtonUp += (s, e) =>
{
mouseDown = false;
AssociatedObject.Child.ReleaseMouseCapture();
};
}
}
If you are not familiar with behaviors, install the Expression Blend 4 SDK and add this namespaces:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
and add System.Windows.Interactivity to your project.
You could open a child Window with a custom border layout. Then add a MouseDown handler that enables the dragging:
<Window
WindowStyle="None"
ShowInTaskbar="False"
ResizeMode="NoResize"
SizeToContent="Height"
MouseDown="Window_MouseDown">
...
</Window>
In code behind:
private void Window_MouseDown(Object sender, MouseButtonEventArgs e)
{
this.DragMove();
}
I have a data template with a textbox and a button with some styles on it. I would like to have the button show the mouse over state when focus is on the textbox beside it. Is this possible?
I figure it would involve something like this. I can get the textbox through use of FindVisualChild and FindName. Then I can set the GotFocus event on the textbox to do something.
_myTextBox.GotFocus += new RoutedEventHandler(TB_GotFocus);
Here in TB_GotFocus I'm stuck. I can get the button I want to show the mouse over state of, but I don't know what event to send to it. MouseEnterEvent isn't allowed.
void TB_GotFocus(object sender, RoutedEventArgs e)
{
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(this.DataTemplateInstance);
DataTemplate template = myContentPresenter.ContentTemplate;
Button _button= template.FindName("TemplateButton", myContentPresenter) as Button;
_button.RaiseEvent(new RoutedEventArgs(Button.MouseEnterEvent));
}
I don't think it's possible to fake the event but you can force the button to render itself as if it had MouseOver.
private void tb_GotFocus(object sender, RoutedEventArgs e)
{
// ButtonChrome is the first child of button
DependencyObject chrome = VisualTreeHelper.GetChild(button, 0);
chrome.SetValue(Microsoft.Windows.Themes.ButtonChrome.RenderMouseOverProperty, true);
}
private void tb_LostFocus(object sender, RoutedEventArgs e)
{
// ButtonChrome is the first child of button
DependencyObject chrome = VisualTreeHelper.GetChild(button, 0);
chrome.ClearValue(Microsoft.Windows.Themes.ButtonChrome.RenderMouseOverProperty);
}
you need to reference PresentationFramework.Aero.dlll for this to work and then it will only work on Vista for the Aero theme.
If you want it to work for other themes you should make a custom controltemplate for each of the theme you want to support.
See http://blogs.msdn.com/llobo/archive/2006/07/12/663653.aspx for tips
As a follow up to jesperll's comment, I think you can get around making a custom template for each theme by dynamically setting the style to the one you want / null.
Here is my window, with the style defined (but not set to anything).
<Window x:Class="WpfApplication.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<Style TargetType="{x:Type Button}" x:Key="MouseOverStyle">
<Setter Property="Background">
<Setter.Value>Green</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid Height="30">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="MyTextBox" Grid.Column="0" Text="Some Text" Margin="2" GotFocus="TextBox_GotFocus" LostFocus="MyTextBox_LostFocus"/>
<Button x:Name="MyButton" Grid.Column="1" Content="Button" Margin="2" MouseEnter="Button_MouseEnter" MouseLeave="Button_MouseLeave" />
</Grid>
Instead of setting the style via triggers in the template, you can use events in your .cs file like so:
...
public partial class Window1 : Window
{
Style mouseOverStyle;
public Window1()
{
InitializeComponent();
mouseOverStyle = (Style)FindResource("MouseOverStyle");
}
private void TextBox_GotFocus(object sender, RoutedEventArgs e) { MyButton.Style = mouseOverStyle; }
private void MyTextBox_LostFocus(object sender, RoutedEventArgs e) { MyButton.Style = null; }
private void Button_MouseEnter(object sender, MouseEventArgs e) { ((Button)sender).Style = mouseOverStyle; }
private void Button_MouseLeave(object sender, MouseEventArgs e) { ((Button)sender).Style = null; }
}
You get a reference to the style in the constructor and then dynamically set it / unset it. This way, you can define what you want your style to look like in Xaml, and you don't have to rely on any new dependencies.