This question already has answers here:
Command for WPF TextBox that fires up when we hit Enter Key
(5 answers)
Closed 9 years ago.
I have a simple requirment in C# WPF. I got a textbox in which I will enter some text. When I press Enter, I want an event to be fired. My code is
private void AddKeyword(object sender, KeyEventArgs e)
{
if(e.Key == Key.Enter)
{
//DO something
}
}
I have set my Textbox AcceptReturn =True; The Method is simply not working and I dont see any event fired when I press Enter. Please Help me out. Thanks in Advance
This work fine for me
<Window x:Class="WpfApplication1.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>
<TextBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBox1" VerticalAlignment="Top" Width="190" KeyUp="textBox1_KeyUp" />
</Grid>
</Window>
and
using System.Windows;
using System.Windows.Input;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
e.Handled = true;
MessageBox.Show("Enter Fired!");
}
}
}
}
Related
I created a new WPF app in Visual Studio and I placed a button using the drag and drop editor but I can't access the button in my .cs file using
MainButton.Content = "Set output to red";
but I get an error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
MainButton was null while running the application.
The drag and drop editor generated this xaml file
<Window x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Border HorizontalAlignment="Center" VerticalAlignment="Center" BorderBrush="Black" BorderThickness="3">
<TextBlock x:Name="Output" Background="Transparent" TextAlignment="Center" TextWrapping="Wrap" Text="Output" Height="88" Width="264"/>
</Border>
<RadioButton x:Name="Option1" Content="Red Pill" HorizontalAlignment="Left" Margin="135,75,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked" IsChecked="True"/>
<RadioButton x:Name="Option2" Content="Blue Pill" HorizontalAlignment="Left" Margin="536,72,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked_1"/>
<Button x:Name="MainButton" Content="Set output to red" HorizontalAlignment="Left" Margin="279,100,0,0" VerticalAlignment="Top" Width="213" Height="41" Click="MainButton_Click"/>
</Grid>
</Window>
Here's the .cs file
using System.Windows;
using System.Windows.Media;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MainButton_Click(object sender, RoutedEventArgs e)
{
if ((bool)Option1.IsChecked)
{
Output.Background = Brushes.Crimson;
}
else
{
Option2.IsChecked = true;
Output.Background = Brushes.DodgerBlue;
}
}
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
MainButton.Content = "Set output to red";
}
private void RadioButton_Checked_1(object sender, RoutedEventArgs e)
{
MainButton.Content = "Set output to blue";
}
}
}
I can access other things in the UI just fine like radio buttons and text blocks but not the button. Why could this be happening?
During the initialization phase, some variables are going to be null since it hasn't been reached in the call order. RadioButton_Checked is called through event before the button is constructed since it contains the Checked property.
A quick and easy fix is as follows: Check for null in your event calls.
private void RadioButton_Checked (object sender, RoutedEventArgs e)
{
if(MainButton != null)
MainButton.Content = "Set output to red";
}
private void RadioButton_Checked_1 (object sender, RoutedEventArgs e)
{
if (MainButton != null)
MainButton.Content = "Set output to blue";
}
Of course, there are better ways to handle this. You could set checked on a separate event, Initialized, which will handle it much cleaner.
can not make it work, whatever I tried so far.
I want to make a Remote Camera Commander application (WPF/C#) in Visual Studio 2015 that consists of a number buttons that, when clicked, do a web request to a network camera. I am not a programmer, so I am starting from scratch.
Have searched the internet for many days now and tested many examples, but when inserting a piece of example code into my code, always new issues arise.
I have made an example that hopefully explains my issues:
MainWindow.xaml:
<Window x:Class="RCC_1v1.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:RCC_1v1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button x:Name="button" Content="GetCameraType_Button" Click="GetType" HorizontalAlignment="Left" Margin="44,108,0,0" VerticalAlignment="Top" Width="168" Height="86"/>
<RichTextBox x:Name="response" HorizontalAlignment="Left" Height="78" VerticalAlignment="Top" Width="169" Margin="246,112,0,0" TextChanged="response_TextChanged">
<FlowDocument>
<Paragraph>
<Run Text ="How to get the response from webclient into this textbox, instead of in the messagebox??"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
</Grid>
MainWindow.xaml.cs:
using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
namespace RCC_1v1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private void GetType(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("stackO", "12345");
wc.DownloadStringAsync(new Uri("http://eremote-cam1.eu.ngrok.io/axis-cgi/param.cgi?action=list&group=root.Brand"));
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
}
private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result.ToString());
}
private void response_TextChanged(object sender, TextChangedEventArgs e)
{
}
}
}
You can run it yourself with the temp. the account that is embedded. Not sure if I should use TextBox or any other object like listview or.
The expected responses are text-string and single numbers.
Any tip, direction or help is appreciated.
Just followed some of your suggestions, code is now:
enter code hereusing System;
using System.Net;
using System.Windows;
namespace RCC_1v2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private void GetType(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("stackO", "54321");
wc.DownloadStringAsync(new Uri("http://eremote-cam1.eu.ngrok.io/axis-cgi/param.cgi?action=list&group=root.Brand.ProdFullName"));
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
}
private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
this.Dispatcher.BeginInvoke(new Action(() => {
String run_text = e.Result.ToString();
Run1.Text = run_text.Substring(24, 13);
}));
}
}
}
enter image description here
Give the name "Run1" to the Run contained in your XAML using x:Name attribute.
Replace your code:
MessageBox.Show(e.Result.ToString());
with this one:
this.Dispatcher.BeginInvoke(new Action(() => {
this.Run1.Text = e.Result.ToString();
}));
The event DownloadStringCompleted runs in a background thread, so if you want to update the UI you must use the Dispatcher property of the Window class.
Ok I just found out about the idea of posting an answer. With help of the posters I created the next example/solution:
using System;
using System.Net;
using System.Windows;
namespace RCC_1v2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private void GetType(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("xxx", "xxx");
wc.DownloadStringAsync(new Uri("http://eremote-cam1.eu.ngrok.io/axis-cgi/param.cgi?action=list&group=root.Brand.ProdFullName"));
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
}
private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
this.Dispatcher.BeginInvoke(new Action(() => {
String run_text = e.Result.ToString();
Run1.Text = run_text.Substring(24, 13);
}));
}
}
}
Mainwindow.xaml:
<Window x:Class="RCC_1v2.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:RCC_1v2"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button x:Name="button" Content="GetCameraType_Button" Click="GetType" HorizontalAlignment="Left" Margin="44,108,0,0" VerticalAlignment="Top" Width="140" Height="86"/>
<TextBox x:Name="Run1" HorizontalAlignment="Left" Height="78" VerticalAlignment="Top" Width="285" Margin="206,113,0,0" >
</TextBox>
</Grid>
</Window>
As you can see I now have the response in the texbox (and not a RichTextBox)
nb. I was not allowed to post a picture :-(
enter image description here
Thanks!
I created 2 button in WPF window and also added mouse down and mouse up event for both buttons. I did mouse down on one button and mouse up on second. but i am getting same first button object to event handler in both events. My question is why i am not getting the second button object in mouse up event.
This is my XAML
<Window x:Class="MouseDownUpSample.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>
<Button x:Name="but1" Content="source" HorizontalAlignment="Left" Margin="86,68,0,0" VerticalAlignment="Top" Width="75" PreviewMouseLeftButtonDown="Button_MouseDown" PreviewMouseLeftButtonUp="Button_MouseUp" />
<Button x:Name="but2" Content="destination" HorizontalAlignment="Left" Margin="406,164,0,0" VerticalAlignment="Top" Width="75" PreviewMouseLeftButtonDown="Button_MouseDown" PreviewMouseLeftButtonUp="Button_MouseUp"/>
</Grid>
Code
public partial class MainWindow : Window
{
string source = null;
string destination = null;
public MainWindow()
{
InitializeComponent();
}
private void Button_MouseDown(object sender, MouseButtonEventArgs e)
{
Button src=sender as Button;
source = src.Content as string;
}
private void Button_MouseUp(object sender, MouseButtonEventArgs e)
{
Button src = sender as Button;
destination = src.Content as string;
if(destination.Equals(source))
{
}
}
I am trying to transfer data from one object to another through drag & drop
My question is why i am not getting the second button object in mouse up event.
Because this is how buttons work.
Taken from MSDN:
If a mouse button is pressed while the pointer is over a form or control, that object "captures" the mouse and receives all mouse events up to and including the last MouseUp event.
This might also interest you:
If mouse buttons are pressed in succession, the object that captures the mouse after the first press receives all mouse events until all buttons are released.
Mouse.MouseDown occurs when any mouse button is pressed, where as Mouse.MouseUp occurs when any mouse button is released. So when you click a button MouseUp event is always followed by MouseDown event since they are sequential events. Hence your if() condition is always true in this case.
if(destination.Equals(source))
{
//always executed;
}
I achieved my goal through WPF drag & drop using DragDropEffects.Copy
XAML
<Window x:Class="MouseDownUpSample.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>
<Button x:Name="but1" Content="source" HorizontalAlignment="Left" Margin="86,68,0,0" VerticalAlignment="Top"
Width="75" PreviewMouseMove="but_MouseMove" AllowDrop="True" PreviewDrop="but_Drop" />
<Button x:Name="but2" Content="destination" HorizontalAlignment="Left" Margin="406,164,0,0" VerticalAlignment="Top"
Width="75" PreviewMouseMove="but_MouseMove" AllowDrop="True" PreviewDrop="but_Drop"/>
</Grid>
CODE
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void but_MouseMove(object sender, MouseEventArgs e)
{
Button src=sender as Button;
if (src != null && e.LeftButton == MouseButtonState.Pressed)
{
DragDrop.DoDragDrop(src,
src.Content.ToString(),
DragDropEffects.Copy);
}
}
private void but_Drop(object sender, DragEventArgs e)
{
Button dest = sender as Button;
string destinationContent = null;
destinationContent = dest.Content as string;
if (dest != null)
{
if (e.Data.GetDataPresent(DataFormats.StringFormat))
{
string sourceContent = (string)e.Data.GetData(DataFormats.StringFormat);
if (destinationContent.Equals(sourceContent))
{
Console.WriteLine("equal");
}
}
}
}
}
I am trying to build a chat application, I would like to mimic facebook tag friends functionality. When the user types # in the textblock, I want to pop a context menu with a list of items. How can this be triggered in wpf mvvm app?
Example.
I would do it the following way :
Subscribe to the TextChanged event and whenever there is a change that contains # then show the popup, otherwise hide it.
Note that it tracks for new changes in the TextBox, therefore the popup will disappear as soon as the user presses another key or in your case when the user selected a user from the auto-completion you have provided in the pop-up.
User hasn't typed #
User just typed #
<Window x:Class="WpfApplication11.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>
<Popup x:Name="MyPopup" Placement="Center">
<Popup.Child>
<Border BorderBrush="Red" BorderThickness="1" Background="White">
<Grid>
<TextBlock>My popup</TextBlock>
</Grid>
</Border>
</Popup.Child>
</Popup>
<TextBox TextChanged="TextBoxBase_OnTextChanged" />
</Grid>
</Window>
Code behind:
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication11
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void TextBoxBase_OnTextChanged(object sender, TextChangedEventArgs e)
{
var textBox = (TextBox) sender;
foreach (TextChange textChange in e.Changes)
{
string substring = textBox.Text.Substring(textChange.Offset, textChange.AddedLength);
if (substring == "#")
{
MyPopup.IsOpen = true;
}
else
{
MyPopup.IsOpen = false;
}
}
}
}
}
That said, you might want to further enhance it and integrate it properly your application ;-)
I have a System.Windows.Controls.TextBox which I would like to behave as follows: When you click it, it is determined dynamically if the TextBox gets focus or not. Here's a toy application which contains a failed attempt at accomplishing this:
<!-- MainWindow.xaml -->
<Window x:Class="Focus.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></RowDefinition>
</Grid.RowDefinitions>
<Label Name="myLabel" Grid.Row="0" Background="Red"></Label>
<TextBox Name="myTextbox" Grid.Row="1" Background="Green"></TextBox>
</Grid>
</Window>
// MainWindow.xaml.cs
using System;
using System.Windows;
using System.Windows.Input;
namespace Focus
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
myTextbox.PreviewGotKeyboardFocus += myTextbox_GotKeyboardFocus;
}
private static readonly Random myRandom = new Random();
private void myTextbox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
int randomInt = myRandom.Next(0, 2); // 0 or 1
myLabel.Content = randomInt;
if(randomInt==0)
{
// PREVENT FOCUS - INSERT CODE HERE. (The line below is a failed attempt.)
FocusManager.SetFocusedElement(this, myLabel);
}
}
}
}
The following code seems to do the trick:
// PREVENT FOCUS - INSERT CODE HERE.
myLabel.Focusable = true;
myLabel.Focus();
myLabel.Focusable = false;
I also changed this line of code:
myTextbox.PreviewGotKeyboardFocus += myTextbox_GotKeyboardFocus;
into this:
myTextbox.GotFocus += myTextbox_GotKeyboardFocus;
I hope you know that you hooked up to the keyboard focus (TAB key).
void textBox1_GotFocus(object sender, System.EventArgs e)
{
if (!this.checkBox1.Checked)
this.checkBox1.Focus();
else
this.textBox1.Focus();
}