E.Handled Not Work From TouchEventArgs in ShowDialog - c#

I've got some trouble with stoping tunneling with Touch when a window was launched with ShowDialog().
My problem is : When I Touch the button in my Window, the clic(or touch ) continue to the MainWindow and open a new Window if antoher Button is behind.
I try to use
e.Handle = true;
To stop tunneling, it work if i clic with my mouse, but if i touch my screen it don't.
Here is a sample Of Code : ( This sample Window have just one button 'OK'. )
C#
public partial class MessageWindow : Window
{
.... other code ...
public static MessageBoxResult Show(string caption, MessageTypes type, MessageBoxButton buttons)
{
MessageWindow wnd = new MessageWindow();
wnd.Owner = Application.Current.MainWindow;
wnd.Title = "Error Message";
wnd.IsError = true;
wnd.Message = caption;
wnd.IsOk = true;
wnd.ShowDialog();
return wnd.Result;
}
private void OnOK()
{
Result = MessageBoxResult.OK;
this.DialogResult = true;
}
private void _btOK_Click(object sender, RoutedEventArgs e)
{
e.Handled = true;
OnOK();
}
private void _btOKonly_TouchDown(object sender, TouchEventArgs e)
{
e.Handled = true;
OnOK();
}
.... other code again ....
}
XAML
<Grid x:Name="LayoutRoot" Background="White" Width="640" Height="480">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Border Background="Black" Padding="20,10">
<TextBlock TextWrapping="Wrap" Text="{Binding Title, ElementName=Window}"/>
</Border>
<Button x:Name="_btOKonly" Content="OK" Click="_btOK_Click" TouchDown="_btOK_Click"Grid.Row="2"/>
<StackPanel>
< ... text of error ...>
</StackPanel>
</Grid>
Here is the code to launch my window :
C#
MessageWindow.Show(" This is a sample of error message", MessageWindow.MessageTypes.Error);
Thanks EveryOne Can Help Me :)

Finaly I found my Answer.
In fact i have to just captur "Clic" and not the "Touch" action like this
<Button x:Name="_btOKonly" Content="OK" Click="_btOK_Click" Grid.Row="2"/>
And The "Clic" is Handle like it does.

Related

Custom Content Dialog in UWP with 3+ buttons

I'd like to display a content dialog box that has more than the traditional Primary and Secondary results. Since I can't override the ContentDialogResult enum and add options to that property, it seems my only choice may be to create my own custom control that works similarly to a ContentDialog.
For additional context: Often, one might see a Dialog box show up during a computer/app operation, when the action is redundant, i.e. copying files to a folder, the computer generally offers a dialog box with not 2 options, but 4. -> "Yes to All", "No to All", "Yes", "No". I can't seem to find any cookie cutter ways to take advantage of this seemingly common practice.
I'd like to use it just the same as a normal Content Dialog like so:
var dialog = new MyCustomContentDialog();
var result = dialog.ShowAsync();
and then return an enum just as the normal ContentDialog but instead have it return 1 of 4 options, not just 2.
Any help or recommendations would be great. Thanks.
I'd like to display a content dialog box that has more than the traditional Primary and Secondary results.
The ContentDialog has 2 built-in buttons(the primary/secondary button) that let a user respond to the dialog. If you want more buttons to let the user to respond to the dialog, you should be able to achieve this by including these buttons in the content of the dialog.
Following is a simple sample shows how to create and use a custom dialog with 3 button:
MyCustomContentDialog.xaml
<ContentDialog
x:Class="ContentDialogDemo01.MyCustomContentDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ContentDialogDemo01"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Name="dialog"
Title="Delete">
<!-- Content body -->
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Margin="0,20">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="200" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.ColumnSpan="3" Text="Delete file A?" Margin="5" />
<Button Grid.Row="1" Content="Yes" x:Name="btn1" Click="btn1_Click" Margin="5,0" Width="100" />
<Button Grid.Row="1" Grid.Column="1" Content="No" x:Name="btn2" Click="btn2_Click" Margin="5,0" Width="100" />
<Button Grid.Row="1" Grid.Column="2" Content="Cancle" x:Name="btn3" Click="btn3_Click" Margin="5,0" Width="100" />
</Grid>
</ContentDialog>
MyCustomContentDialog.xaml.cs
namespace ContentDialogDemo01
{
// Define your own ContentDialogResult enum
public enum MyResult
{
Yes,
No,
Cancle,
Nothing
}
public sealed partial class MyCustomContentDialog : ContentDialog
{
public MyResult Result { get; set; }
public MyCustomContentDialog()
{
this.InitializeComponent();
this.Result = MyResult.Nothing;
}
// Handle the button clicks from dialog
private void btn1_Click(object sender, RoutedEventArgs e)
{
this.Result = MyResult.Yes;
// Close the dialog
dialog.Hide();
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
this.Result = MyResult.No;
// Close the dialog
dialog.Hide();
}
private void btn3_Click(object sender, RoutedEventArgs e)
{
this.Result = MyResult.Cancle;
// Close the dialog
dialog.Hide();
}
}
}
Here is the code to show the custom dialog and use returned custom result:
private async void ShowDialog_Click(object sender, RoutedEventArgs e)
{
// Show the custom dialog
MyCustomContentDialog dialog = new MyCustomContentDialog();
await dialog.ShowAsync();
// Use the returned custom result
if (dialog.Result == MyResult.Yes)
{
DialogResult.Text = "Dialog result Yes.";
}
else if (dialog.Result == MyResult.Cancle)
{
DialogResult.Text = "Dialog result Canceled.";
}
else if (dialog.Result == MyResult.No)
{
DialogResult.Text = "Dialog result NO.";
}
}
Here is the entire sample. Following is the output:
Just for completeness - the ContentDialog class by default actually offers three buttons - Primary, Secondary and Close. Close is what is triggered when the user presses escape, but if you set CloseButtonText the button will show up as the third button in the dialog's footer.

How to diplay/call an UserControl from another UserControl at click both situated in one MainWindow (C#/Xaml)

I'm pretty stuck right now, i'm gonna explain my problem and what i want.
In my solution i have a mainWindow, in that MainWindow i call the first userControl Who is situated in an userControlLibrary. I'ts a menu with button. I want when i click on the first button of the first userControl, i want put the visibility of the second usercontrol to visible (too situated in the userControlLibrary). But i try many things but no one works.
The first userControl is UC_MenuSlider and UC_Start_Study is the second who have to be visibile after click on the button on the first one. At launch UC_Start_Study is hidden.
This is a part of the code of my Mainwindow:
<Grid Name="MainGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<UserControlLibrary:UC_StartStudy x:Name="UC_Start_Study" Grid.Column="1" Height="Auto" Width="Auto" Margin="70 0 0 0" Visibility="Hidden"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.1*" MaxWidth="240" MinWidth="240" />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<UserControlLibrary:UC_MenuSlider x:Name="UC_MenuSlider" Grid.Column="0"/>
</Grid>
</Grid>
A part of the code of my first UserControl (UC_MenuSlider):
<Grid Name="Grid_Menu" HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button x:Name="Start_Study" Grid.Row="0" Grid.Column="0" Margin="0" Content="Start Study" FontSize="16" Click="Start_Study_Click">
</Button>
</Grid>
At first a basic event,just an event click in my first userControl. with code behind like that:
public void Start_Study_Click(object sender, RoutedEventArgs e)
{
var startStudy = new UserControlLibrary.UC_StartStudy();
startStudy.Visibility = Visibility.Visible;
}
Don't works. Then i use 'RoutedEvent' But I don't really understand who it works.
I hope my question was enough clear, thanks in advance for your anwsers
The problem is because you are creating a new UC_StartStrudy and set its Visibility to Visible. What you really need is to set Visibility of the one in your XAML: UC_Start_Study
public void Start_Study_Click(object sender, RoutedEventArgs e)
{
UC_Start_Study.Visibility = Visibility.Visible;
}
And you could also use XAML databinding the Visibility property of your UC_StartStrudy, and set its value in your code:
XAML:
<Window.Resourses>
<BooleanToVisibilityConverter x:Key="BooltoVisible" />
</Window.Resourse>
.....
<UserControlLibrary:UC_StartStudy x:Name="UC_Start_Study" Grid.Column="1" Height="Auto" Width="Auto" Margin="70 0 0 0" Visibility="{Binding IsUCStartStudyVisible, Converter={StaticResource BooltoVisible}}"/>
Code (remember to implement INotifyPropertyChanged ):
//implement INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChange(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
//property for data binding
private bool _isucstartstudyvisible = false;
public bool IsUCStartStudyVisible
{
get{return _isucstartstudyvisible;}
set{_isucstartstudyvisible=value; RaisePropertyChange("IsUCStartStudyVisible");}
}
//your event to change the visibility
public void Start_Study_Click(object sender, RoutedEventArgs e)
{
IsUCStartStudyVisible=true;
}
I don't understand why you are taking a new instance of UC_StartStudy() as you have already added this in your MainWindow.
Can't you simply turn the visibility of UC_Start_Study as visible within the code.
Let me show you how you can do this.
try
public void Start_Study_Click(object sender, RoutedEventArgs e)
{
this.UC_Start_Study.Visibility = Visibility.Visible;
}

What event fires when user lifts finger from ScrollViewer on touch capable screens

I'm finding that when I tap the ScrollViewer, the PointerPressed and PointerExited events fires as expected. But, if I scroll in any direction after touching the screen and lift my finger, no event fires except for PointerCaptureLost which prematurely fires as soon as I scroll.
When I capture the pointer ID and poll the status of the PointerPoint with a timer, the IsInContact flag remains true, even after I lift my finger after scrolling. It works as expected when I simply tap the screen.
ManipulationCompleted has the same effect as above, and I cannot use the ViewChanged event since this fires before I lift my finger.
Is this a bug or am I missing something here? Is there another way I can detect when a user has lifted their finger off the screen? This is driving me bananas.
Sample code below. You'll need to use the simulator in touch-mode or have a touch capable screen to test:
Code:
using System;
using Windows.UI.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
namespace App1
{
public sealed partial class MainPage : Page
{
private readonly DispatcherTimer pointerTimer = new DispatcherTimer();
private uint? CurrentPointerID; //container for the current pointer id when user makes contact with the screeen
public MainPage()
{
this.InitializeComponent();
scrollviewer.PointerPressed += scrollviewer_PointerPressed;
scrollviewer.PointerMoved += scrollviewer_PointerMoved;
scrollviewer.PointerExited += scrollviewer_PointerExited;
scrollviewer.PointerReleased += scrollviewer_PointerReleased;
scrollviewer.PointerCaptureLost += scrollviewer_PointerCaptureLost;
scrollviewer.PointerCanceled += scrollviewer_PointerCanceled;
pointerTimer.Tick += pointerTimer_Tick;
pointerTimer.Interval = TimeSpan.FromMilliseconds(300);
pointerTimer.Start();
}
#region ScrollViewer Events
void scrollviewer_PointerMoved(object sender, PointerRoutedEventArgs e)
{
EventCalledTextBlock.Text = "Pointer Moved";
}
void scrollviewer_PointerExited(object sender, PointerRoutedEventArgs e)
{
EventCalledTextBlock.Text = "Pointer Exited";
}
void scrollviewer_PointerPressed(object sender, PointerRoutedEventArgs e)
{
CurrentPointerID = e.Pointer.PointerId;
EventCalledTextBlock.Text = "Pointer Pressed";
}
void scrollviewer_PointerCanceled(object sender, PointerRoutedEventArgs e)
{
EventCalledTextBlock.Text = "Pointer Canceled";
}
void scrollviewer_PointerCaptureLost(object sender, PointerRoutedEventArgs e)
{
EventCalledTextBlock.Text = "Capture Lost";
}
void scrollviewer_PointerReleased(object sender, PointerRoutedEventArgs e)
{
EventCalledTextBlock.Text = "Pointer Released";
}
#endregion
void pointerTimer_Tick(object sender, object e)
{
if (!CurrentPointerID.HasValue)
{
PollingTextBlock.Text = string.Empty;
return;
}
try
{
var pointerPoint = PointerPoint.GetCurrentPoint(CurrentPointerID.Value);
PollingTextBlock.Text = pointerPoint.IsInContact ? "Is In Contact" : "Not in Contact";
}
catch (Exception ex)
{
//This exception is raised when the user lifts finger without dragging.
//assume finger is not in contact with screen
PollingTextBlock.Text = "Not in Contact";
}
}
}
}
XAML:
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Name="grid">
<Grid.RowDefinitions>
<RowDefinition Height="113*"/>
<RowDefinition Height="655*"/>
</Grid.RowDefinitions>
<ScrollViewer x:Name="scrollviewer" VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Visible" Grid.Row="1" >
<Rectangle Fill="#FF3783CF" Height="100" Stroke="#FF33D851" Width="{Binding ElementName=grid, Path=ActualWidth}" Margin="100" StrokeThickness="4" />
</ScrollViewer>
<StackPanel Orientation="Vertical" Margin="45,25,0,0">
<StackPanel Orientation="Horizontal">
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="Event Called:" VerticalAlignment="Top" FontSize="24" Margin="0,0,20,0"/>
<TextBlock x:Name="EventCalledTextBlock" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="24"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="Polling Value:" VerticalAlignment="Top" FontSize="24" Margin="0,0,20,0"/>
<TextBlock x:Name="PollingTextBlock" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="24"/>
</StackPanel>
</StackPanel>
</Grid>
</Page>
I stumbled upon this question since I was struggling with a similar problem. I have a ScrollViewer which has several images in it and I wanted to know what images are shown at the moment the ScrollViewer stops moving...
In the end I did used the ScrollViewer.ViewChanged event. This event keeps triggering untill it has finished with scrolling.
I actually am only interested in the last of these events, but since there is no event that triggers only on that particular moment I need to respond to this one and check for myself if this is the appropriate moment to take actions.
I hope this helps.
ScrollViewer.ViewChanged event: https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.scrollviewer.viewchanged?f=255&MSPPError=-2147217396
I think you need to use the PointerReleased event.
Refer to the following link: https://msdn.microsoft.com/library/windows/apps/br208279

Setting control to be content of several controls

I have a control which i'm putting in dialog as a content. Due to relization of this dialog i have to create it every time when i need it(Show/Hide won't do the trick). I want my control to remember field content beetween calls. While i can apply viewmodel to achieve this i prefer just keep control as a field and assing it as content of dialog every time i need it. But i run into following error:
"Specified element is already the logical child of another element. Disconnect it first."
I tried to assing null to dialog window's content before closing it, but it doesn't solve the problem. Is there anything i can do?
Setting window.Content = null works fine for me. Following is the code I used:
public partial class MainWindow : Window
{
TextBlock textBlock = new TextBlock();
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
TestWindow testWindow = new TestWindow();
testWindow.Content = textBlock;
testWindow.Closing += HandleTestWindowClosing;
testWindow.Show();
}
void HandleTestWindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
var testWindow = sender as TestWindow;
if(testWindow!=null)
{
testWindow.Content = null;
testWindow.Closing -= HandleTestWindowClosing;
}
}
}
Check out the following working example. It isn't exactly your scenario, but pretty close. The key is setting the 'Child' property to null. It moves the TextBox from the top border to the bottom.
<Window x:Class="SO.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>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Button Grid.Row="0" Click="Move_Click">Move</Button>
<Border x:Name="topBorder" Grid.Row="1">
<TextBlock x:Name="ctrl">Some Text Block</TextBlock>
</Border>
<Border x:Name="bottomBorder" Grid.Row="2"/>
</Grid>
</Window>
and the code behind:
using System.Windows;
namespace SO
{
public partial class MainWindow :Window
{
public MainWindow( )
{
InitializeComponent( );
}
private void Move_Click( object sender, RoutedEventArgs e )
{
this.topBorder.Child = null;
this.bottomBorder.Child = this.ctrl;
}
}
}

Enter key pressed event handler

I want to capture the text from the textbox when enter key is hit. I am using WPF/visual studio 2010/.NET 4. I dont know what event handler to be used in the tag ? I also want to do the same for maskedtextbox.
Either KeyDown or KeyUp.
TextBox tb = new TextBox();
tb.KeyDown += new KeyEventHandler(tb_KeyDown);
static void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//enter key is down
}
}
You can also use PreviewKeyDown in WPF:
<TextBox PreviewKeyDown="EnterClicked" />
or in C#:
myTextBox.PreviewKeyDown += EnterClicked;
And then in the attached class:
void EnterClicked(object sender, KeyEventArgs e) {
if(e.Key == Key.Return) {
DoSomething();
e.Handled = true;
}
}
The KeyDown event only triggered at the standard TextBox or MaskedTextBox by "normal" input keys, not ENTER or TAB and so on.
One can get special keys like ENTER by overriding the IsInputKey method:
public class CustomTextBox : System.Windows.Forms.TextBox
{
protected override bool IsInputKey(Keys keyData)
{
if (keyData == Keys.Return)
return true;
return base.IsInputKey(keyData);
}
}
Then one can use the KeyDown event in the following way:
CustomTextBox ctb = new CustomTextBox();
ctb.KeyDown += new KeyEventHandler(tb_KeyDown);
private void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Enter key is down
//Capture the text
if (sender is TextBox)
{
TextBox txb = (TextBox)sender;
MessageBox.Show(txb.Text);
}
}
}
In WPF, TextBox element will not get opportunity to use "Enter" button for creating KeyUp Event until you will not set property: AcceptsReturn="True".
But, it would`t solve the problem with handling KeyUp Event in TextBox element. After pressing "ENTER" you will get a new text line in TextBox.
I had solved problem of using KeyUp Event of TextBox element by using Bubble event strategy. It's short and easy. You have to attach a KeyUp Event handler in some (any) parent element:
XAML:
<Window x:Class="TextBox_EnterButtomEvent.MainWindow"
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:TextBox_EnterButtomEvent"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid KeyUp="Grid_KeyUp">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height ="0.3*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="1" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow">
Input text end press ENTER:
</TextBlock>
<TextBox Grid.Row="2" Grid.Column="1" HorizontalAlignment="Stretch"/>
<TextBlock Grid.Row="4" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow">
You have entered:
</TextBlock>
<TextBlock Name="txtBlock" Grid.Row="5" Grid.Column="1" HorizontalAlignment="Stretch"/>
</Grid></Window>
C# logical part (KeyUp Event handler is attached to a grid element):
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Grid_KeyUp(object sender, KeyEventArgs e)
{
if(e.Key == Key.Enter)
{
TextBox txtBox = e.Source as TextBox;
if(txtBox != null)
{
this.txtBlock.Text = txtBox.Text;
this.txtBlock.Background = new SolidColorBrush(Colors.LightGray);
}
}
}
}
Result:
For those who struggle at capturing Enter key on TextBox or other input control, if your Form has AcceptButton defined, you will not be able to use KeyDown event to capture Enter.
What you should do is to catch the Enter key at form level. Add this code to the form:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if ((this.ActiveControl == myTextBox) && (keyData == Keys.Return))
{
//do something
return true;
}
else
{
return base.ProcessCmdKey(ref msg, keyData);
}
}

Categories