How to update textblock with method - c#

I have a textbox that provide user to input string. how can i pass that string to method and toUpper() it. and pass back the string to textblock in the main window that both of the box and block update in real time?
For my C# code:
public MainWindow()
{
InitializeComponent();
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
textBlock.Text = textBox.Text +"changed";
}
it is just as simple like this.
for my xaml code:
<Grid >
<TextBox x:Name ="textBox" HorizontalAlignment="Left" Height="105" Margin="28,185,0,0" TextWrapping="Wrap" Text="HELLO" VerticalAlignment="Top" Width="300" TextChanged="TextBox_TextChanged"/>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Height="116" Margin="114,40,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="328"/>
</Grid>
i want to know why the text of my textblock cannot be updated when i type something inside the textbox.

I combined the answer of #Yavor Georgiev
You are encountering a null reference exception. When the textBox control is created it will trigger the textChange event on textBox and by that point, textBlock isn't created and is therefore null. You can just change the order of the textboxes in the XAML and you will be fine.
Change the order
Grid>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Height="116" Margin="114,40,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="328"/>
<TextBox x:Name ="textBox" HorizontalAlignment="Left" Height="105" Margin="28,185,0,0" TextWrapping="Wrap" Text="HELLO" VerticalAlignment="Top" Width="300" TextChanged="TextBox_TextChanged"/>
</Grid>
For the upper part i used #Yavor Georgiev answer when typing
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
textBox.Text = textBox.Text?.ToUpper();
textBlock.Text = textBox.Text;
textBox.CaretIndex = textBox.Text?.Length ?? 0;
textBlock.Text = textBox.Text + "changed";
}

Do you need something like this?
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
textBox.Text = textBox.Text?.ToUpper();
textBlock.Text = textBox.Text;
textBox.CaretIndex = textBox.Text?.Length ?? 0; //You need this to continue typing from the last index onwards..
}
I don't exactly understand if you need both the textBox and the textBlock to change at the same time or only the textBlock to be in UpperCase, but the concept is the same

Related

Using connected animation

<GridView x:Name="ForegroundElement" ItemsSource="{x:Bind Icons}" IsItemClickEnabled="True" ItemClick="Grid_Clicked">
<GridView.ItemTemplate>
<DataTemplate x:DataType="data:Icon">
<StackPanel>
<Image x:Name="ConnectedElement" Width="200" Height="200" HorizontalAlignment="Center" Source="{x:Bind ImageCover}"/>
<TextBlock FontSize="16" VerticalAlignment="Center" Text="{x:Bind Title}"/>
<TextBlock FontSize="10" VerticalAlignment="Center" Text="{x:Bind Room}"/>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
this is my gridView contain the data
and this is my clicked event
private void Grid_Clicked(object sender, ItemClickEventArgs e)
{
var icon = (Icon)e.ClickedItem;
IconResult.Text = "You selected a " + icon.Title;
}
I wanna add the ConnectedAnimation when ever I click a "Stack" in the "GridView" to navigate the other page
Microsoft I have to create the "PrepareConnectedAnimation" method use this
but in my case I have a click event so what should I do to create and use this method ?
It is perfectly ok to put it inside the Clicked event. You first have to get hold of the item container itself. You can do that using the ContainerFromItem method of the GridView:
private void Grid_Clicked(object sender, ItemClickEventArgs e)
{
var icon = (Icon)e.ClickedItem;
IconResult.Text = "You selected a " + icon.Title;
var container = ForegroundElement.ContainerFromItem(e.ClickedItem) as GridViewItem;
if (container != null)
{
//find the image
var root = (FrameworkElement)container.ContentTemplateRoot;
var image = (UIElement)root.FindName("ConnectedElement");
//prepare the animation
ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("Image", image);
}
Frame.Navigate(typeof(SecondPage));
}
Now on the second page you get hold of the animation and connect it:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
ConnectedAnimation imageAnimation =
ConnectedAnimationService.GetForCurrentView().GetAnimation("Image");
imageAnimation?.TryStart(TargetElement);
}
You can check out the exmple provided in the UWP Samples gallery on GitHub to see full implementation in action.

Hyperlink click action and ability to select and copy text

I'm working on a WPF application in C# and need the ability for users to click a hyperlink(execute the command) but also have the ability to select the text and copy it.
I searched for options but could not find anything that would help me.
Currently i have the following in my WPF XAML:
<TextBlock Grid.Column="1" Grid.Row="0">
<Hyperlink Command="{Binding OpenDefaultMailApplicationCommand}" >
<TextBox Height="20" IsReadOnly="True" Foreground="Blue" BorderThickness="0">test#test.nl</TextBox>
</Hyperlink>
</TextBlock>
What am i doing wrong? The text is selectable only i don't have the ability to click on it to execute my command.
This is what I use for similar req.
You need to have a textbox, which is non editable and is clickable. you can style it as a hyperlink by making in underlined and color changes etc.
<TextBox IsReadOnly="True"
Background="Transparent"
BorderThickness="0"
Text="test#test.nl"
Height="20"
PreviewMouseLeftButtonDown="TextBox_PreviewMouseLeftButtonDown"
TextDecorations="Underline"
MouseMove="TextBox_MouseMove"
Foreground="Blue" />
private void TextBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (Keyboard.IsKeyDown(Key.LeftCtrl))
{
MessageBox.Show("CLicked");
}
}
private void TextBox_MouseMove(object sender, MouseEventArgs e)
{
var txtBox = sender as TextBox;
if (Keyboard.IsKeyDown(Key.LeftCtrl))
{
txtBox.Cursor = Cursors.Hand;
}
else
txtBox .Cursor = null;
}
So i found a other approach for the problem.
By using a richtextbox and adding a hyperlink to that, a user is able to select the text but can also click it.
<RichTextBox Name="rtbEmail" Grid.Column="1" Grid.Row="0" Foreground="Blue" BorderThickness="0"
Margin="3"/>
In the 'C#' usercontrol.cs i programmaticly set the hyperlink and add a click eventhandler to it.
FlowDocument doc = new FlowDocument();
rtbEmail.Document = doc;
rtbEmail.IsReadOnly = true;
rtbEmail.IsDocumentEnabled = true;
Paragraph para = new Paragraph();
doc.Blocks.Add(para);
Hyperlink link = new Hyperlink();
link.IsEnabled = true;
link.Inlines.Add(DataContext.EmailAddress);
link.Click += new RoutedEventHandler(this.OpenEmailAppEvent);
para.Inlines.Add(link);
Hopefully someone has use for this :). i did :)

Set Validation at TextBox

How to set Validation error on textbox?
For example if user insert less than 12 word it will display.
If user insert number it will display
Validation I want to display is at Label
<TextBox HorizontalAlignment="Left" Height="23" Margin="41,69,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="200" Grid.Column="1"/>
<Label Content="Label" HorizontalAlignment="Left" Margin="40,176,0,0" VerticalAlignment="Top"/>
use text changed event of Textbox control. you will get the number of words entered in text box using the following code
private void textbox1_TextChanged(object sender, TextChangedEventArgs e)
{
string[] arrWords = textbox1.Text.Split(new char[] { ' ' });
int count = arrWords.Length.ToString();
if(count<12)
{
label1.Content="enter your error message";
}
}

Saving user color settings of a clicked Button in WPF

I have a little problem with saving some properties of my Buttons. The Buttons are small and with a variety of colors. When i press one button, some specified colors are changing... and i want to save them for the next start up. The textbox values i can save them but this ...i can't.
Code:
public MainWindow()
{
InitializeComponent();
//blueColor.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
//this.Property = Properties.Settings.Default.userColor;
}
private void blueColor_Click(object sender, RoutedEventArgs e)
{
var bc = new BrushConverter();
Main.Background = (Brush)bc.ConvertFrom("#FF007CE4");
startButton.Foreground = (Brush)bc.ConvertFrom("#FF007CE4");
closeButton.Foreground = (Brush)bc.ConvertFrom("#FF007CE4");
Properties.Settings.Default.userColor = true;
Properties.Settings.Default.Save();
}
private void purpleColor_Click(object sender, RoutedEventArgs e)
{
var bc = new BrushConverter();
Main.Background = (Brush)bc.ConvertFrom("#FF8701B9");
startButton.Foreground = (Brush)bc.ConvertFrom("#FF8701B9");
closeButton.Foreground = (Brush)bc.ConvertFrom("#FF8701B9");
}
I think I need the last clicked Button to be saved because I have allot of colors and maybe the .RaiseEvent can help here.
This is how it looks like:
Those 3 little buttons:
white
blue
red
are for changing the look of the program. At every start, the default is back.
You can store the color as a simple string and TypeConverter automatically converts it to type Brush. Below is an example.
Binding default value from XAML:
xmlns:properties="clr-namespace:WorkWithSettings.Properties"
<Button Width="100" Height="30"
Background="{Binding Source={x:Static properties:Settings.Default}, Path=Setting, Mode=TwoWay}" />
Set value from code:
private void Button_Click(object sender, RoutedEventArgs e)
{
WorkWithSettings.Properties.Settings.Default.Setting = "#FF007CE4";
}
Note: Setting - this is just the type of String.
More information you can see here:
TypeConverters and XAML
Edit:
Below I'll show you an example, that I hope will help you.
So, go into the settings of the project: Project -> Properties -> Parameters. This opens a window of approximately:
Here we have a property ButtonColor, defined in the settings. For example, I took the Button, which changes the background, depending on the color of the pressed button.
In order to property Background the synchronize with settings to do, so:
<Button Width="100" Height="30"
Content="TestButton"
Background="{Binding Source={x:Static properties:Settings.Default}, Path=ButtonColor, Mode=TwoWay}" />
The default background color of white. Now, to set the background color at the button, we change the parameter settings, like this:
private void Blue_Click(object sender, RoutedEventArgs e)
{
WorkWithSettings.Properties.Settings.Default.ButtonColor = "Blue";
}
To save changes to the settings, you need to call a method Save():
private void Save_Click(object sender, RoutedEventArgs e)
{
WorkWithSettings.Properties.Settings.Default.Save();
}
Now, the next time you start the program, the color will be the one that was set last.
Full example
XAML
<Window x:Class="WorkWithSettings.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:properties="clr-namespace:WorkWithSettings.Properties"
WindowStartupLocation="CenterScreen"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock Width="100" Height="30" Text="{Binding Source={x:Static properties:Settings.Default}, Path=ButtonColor, Mode=TwoWay}" Margin="0,60,0,0" />
<Button Width="100" Height="30" Content="TestButton" Background="{Binding Source={x:Static properties:Settings.Default}, Path=ButtonColor, Mode=TwoWay}" />
<WrapPanel>
<Button Name="Blue" Width="100" Height="30" Content="BlueColor" VerticalAlignment="Top" Click="Blue_Click" />
<Button Name="Red" Width="100" Height="30" Content="RedColor" VerticalAlignment="Top" Click="Red_Click" />
<Button Name="White" Width="100" Height="30" Content="WhiteColor" VerticalAlignment="Top" Click="White_Click" />
</WrapPanel>
<Button Name="Save" Width="60" Height="30" Content="Save" VerticalAlignment="Top" HorizontalAlignment="Right" Click="Save_Click" />
</Grid>
</Window>
Code behind
namespace WorkWithSettings
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void White_Click(object sender, RoutedEventArgs e)
{
WorkWithSettings.Properties.Settings.Default.ButtonColor = "White";
}
private void Blue_Click(object sender, RoutedEventArgs e)
{
WorkWithSettings.Properties.Settings.Default.ButtonColor = "Blue";
}
private void Red_Click(object sender, RoutedEventArgs e)
{
WorkWithSettings.Properties.Settings.Default.ButtonColor = "Red";
}
private void Save_Click(object sender, RoutedEventArgs e)
{
WorkWithSettings.Properties.Settings.Default.Save();
}
}
}
Output
You probably need to create items in the Settings tab of your project that store the information about the color. I would recommend storing the hex strings. Then, on MainForm_Load retrieve those values.
Make sure to also put the settings in the User scope, or else they will reset each time they close the application.

WPF, sibling selection like jQuery?

I have the following XAML code as an example in my WPF application
<StackPanel Height="23" Name="MSpanel" Orientation="Horizontal" Width="138" Margin="37,13,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" >
<TextBox Height="23" Name="MTBox" Width="120" Text="0" />
<ScrollBar Height="23" Name="MSBar" Width="18" TouchUp="SBar_TouchUp" />
</StackPanel>
<StackPanel Height="23" Name="CSPanel" Orientation="Horizontal" Width="138" Margin="37,41,0,0" VerticalAlignment="Top" HorizontalAlignment="Left">
<TextBox Height="23" Name="CTBox" Width="120" Text="0" />
<ScrollBar Height="23" Name="CSBar" Width="18" TouchUp="SBar_TouchUp" />
</StackPanel>
I have this function:
private void SBar_TouchUp(object sender, TouchEventArgs e)
{
//what goes here?
//siblings.getFirst('textbox').text += 1;
}
What I was hoping to do, is have 1 function that controls these "Psudo" numeric up downs in WPF. If there was some way to have a unified function that could, reference the sibling textbox, so I only have to write it once. That would be ideal.
I'm very familiar with jQuery, and XAML looks like an HTML DOM, ... Is there a way to browse the tree?
I realize there are existing Numeric Up Downs available to download. This idea I believe would be good to know for the future in other endeavors as well. Thanks.
The solution that worked!
private void SBar_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (e.NewValue == 0) return; //abort here, no change
ScrollBar sb = (ScrollBar)sender;
StackPanel sp = (StackPanel)sb.Parent;
TextBox tb = (TextBox)sp.Children[0];
int change = e.NewValue < 0 ? 1 : -1;
sb.Value = 0; //this will invoke this function again
tb.Text = (Convert.ToInt32(tb.Text) + change).ToString();
}
Each element in the visual tree has a Parent and VisualParent property - as all elements are based on UIElement - either should give you the parent object.
In this case the parent of the ScrollBar is the StackPanel. You can then use the Children property of the StackPanel to get the collection of child objects. You know which is the ScrollBar (it's the sender) so the other must be the TextBox.
You can do something like this:
private void SBar_TouchUp(object sender, TouchEventArgs e)
{
//siblings.getFirst('textbox').text += 1;
var siblings = ((sender as FrameworkElement).Parent as Panel).Children;
var textbox = siblings.OfType<TextBox>().First();
textbox.Text = (int.Parse(textbox.Text) + 1).ToString();
}
but I would suspect that there are probably better ways to do what you want, like data binding or naming elements in attached properties.
Yeah, there are many properties for both Logical and Visual trees.
Like FrameworkElement.Parent or Panel.Children.
I don't think there is directly method to get sibling, but its not that hard to get index in list of children of parent and getting next item.

Categories