Increment textbox value on button click WPF C# - c#

What I'm trying to do is I have a textbox, and a '-' and a '+' button, and on button click I need to decrease/increase it's value. I have close to 0 experience with WPF, we only learnt console apps in school and now we got this task and I have no idea why this code sample is not working:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace sudokuGUI
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
int ertek = Convert.ToInt32(textBox1.Text);
if (ertek > 4)
{
textBox1.Text = $"{ertek--}";
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
int ertek = Convert.ToInt32(textBox1.Text);
if (ertek < 9)
{
textBox1.Text = $"{ertek++}";
}
}
}
}
<Window x:Class="sudokuGUI.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:sudokuGUI"
mc:Ignorable="d"
Title="Sudoku-ellenőrző" Height="210" Width="540">
<Grid>
<TextBox x:Name="textBox2" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="512" Margin="10,90,0,0"/>
<Label Content="Új feladvány mérete:" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,10,0,0"/>
<Button Content="-" HorizontalAlignment="Left" VerticalAlignment="Top" Width="20" Margin="144,13,0,0" Click="Button_Click"/>
<Button Content="+" HorizontalAlignment="Left" VerticalAlignment="Top" Width="20" Margin="194,13,0,0" Click="Button_Click_1"/>
<Label Content="Kezdőállapot:" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,59,0,0"/>
<Label x:Name="label1" Content="Hossz: 0" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,118,0,0"/>
<Button Content="Ellenőrzés" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="447,118,0,0"/>
<TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="20" TextWrapping="Wrap" Text="4" VerticalAlignment="Top" Width="20" Margin="169,13,0,0" TextAlignment="Center" IsEnabled="False"/>
</Grid>
</Window>
Any help is appreciated!

ertek++ is a postfix increment operator. The result of ertek++ is the value of ertek before the operation.
use simple + operator:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
int ertek = Convert.ToInt32(textBox1.Text);
if (ertek < 9)
{
textBox1.Text = $"{ertek+1}";
}
}

Related

ListBox doesn't refresh?

i have an issue on Visual Studio(wpf) with the listbox.
If i want to insert or delete some data from the database, then they are working,but the listbox will just be refreshed if i'm clicking the menuitem for once. I think this is due to the load method, but why isn't it refreshing the data?
This is my XAML-Code:
<UserControl x:Class="WpfApplication1.AutorenBearbeiten"
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:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
d:DesignHeight="400" d:DesignWidth="300" Loaded="UserControl_Loaded">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="28*" />
<ColumnDefinition Width="36*" />
</Grid.ColumnDefinitions>
<TextBlock Text="Medien" Grid.ColumnSpan="2"
FontSize="16" />
<ListBox x:Name="box" Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=at_nachname}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel DataContext="{Binding ElementName=box,Path=SelectedItem}" Grid.Column="1" Grid.Row="1" >
<TextBlock Text="Autoren_id" />
<TextBox Text="{Binding Path=at_id}" MaxLength="5"/>
<TextBlock Text="Vorname" />
<TextBox Text="{Binding Path=at_vorname}" MaxLength="30"/>
<TextBlock Text="Nachname" />
<TextBox Text="{Binding Path=at_nachname}" MaxLength="30"/>
<TextBlock Text="Geburtsdatum" />
<TextBox MaxLength="30" Text="{Binding Path=at_gebDatum, StringFormat=dd.MM.yyyy}" />
<Button Name="speichern" Height="23" Margin="4" Click="speichern_Click">Änderungen speichern</Button>
<Button Name="loeschen" Height="23" Margin="4" Click="loeschen_Click">Löschen</Button>
<StackPanel DataContext="{Binding ElementName=box}" Grid.Column="1" Grid.Row="1" >
<TextBlock Text="Autoren_id" />
<TextBox x:Name="id" MaxLength="5"/>
<TextBlock Text="Vorname" />
<TextBox x:Name="vorname" MaxLength="30"/>
<TextBlock Text="Nachname" />
<TextBox x:Name="nachname" MaxLength="30"/>
<TextBlock Text="Geburtsdatum" />
<TextBox x:Name="datum" MaxLength="30"/>
<Button x:Name="neubutton" Height="23" Margin="4" Click="neu_Click">Neu</Button>
<TextBlock Name="submitfehler" FontWeight="Bold" Foreground="Red" />
</StackPanel>
</StackPanel>
</Grid>
</UserControl>
And this is the xaml.cs file :
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for AutorenBearbeiten.xaml
/// </summary>
public partial class AutorenBearbeiten : UserControl
{
libraryEntities6 db = new libraryEntities6();
public AutorenBearbeiten()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
var erg = db.a_autor;
erg.Load();
box.ItemsSource = erg.Local.OrderBy(m => m.at_id);
box.ItemsSource =
(from m in db.a_autor
orderby m.at_id
select m).ToList();
}
private void speichern_Click(object sender, RoutedEventArgs e)
{
try
{
db.SaveChanges();
}
catch(Exception e1)
{
submitfehler.Text = e1.Message;
}
}
private void loeschen_Click(object sender, RoutedEventArgs e)
{
a_autor am = (a_autor)box.SelectedItem;
if (am != null)
{
db.a_autor.Remove(am);
db.SaveChanges();
box.Items.Refresh();
}
}
private void neu_Click(object sender, RoutedEventArgs e)
{
a_autor autor = new a_autor();
autor.at_id = id.Text;
autor.at_vorname = vorname.Text;
autor.at_nachname = nachname.Text;
autor.at_gebDatum = Convert.ToDateTime(datum.Text);
//s1.s_k_klasse = liklassen.SelectedValue.ToString() setzt die Klasse via foreign key
//db.schuelers.AddObject(s1);
db.a_autor.Add(autor);
box.Items.Refresh();
/*
((klassen))liklassen.SelectedItem).schuelers.Add(s1); //setzt die klasse durch zuweisen zum nav.Property
lischueler.Items.Refresh(); //nötig weil das navigational seit ER 5 nicht observable ist
*/
}
}
}
A Picture from the window is below:
Window
There is no magic connection between the ListBox and the database so when you are calling the Add or Remove method of the DbContext the ListBox won't be affected.
What you should do is to set the ItemsSource property of the ListBox to an ObservableCollection<a_autor> and then call the Add/Remove method of this one besides calling the Add/Remove method of the DbContext:
System.Collections.ObjectModel.ObservableCollection<a_autor> _sourceCollection;
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
var erg = db.a_autor;
erg.Load();
_sourceCollection = new System.Collections.ObjectModel.ObservableCollection<a_autor>((from m in db.a_autor
orderby m.at_id
select m).ToList());
box.ItemsSource = _sourceCollection;
}
private void loeschen_Click(object sender, RoutedEventArgs e)
{
a_autor am = (a_autor)box.SelectedItem;
if (am != null)
{
_sourceCollection.Remove(am);
db.a_autor.Remove(am);
db.SaveChanges();
box.Items.Refresh();
}
}
private void neu_Click(object sender, RoutedEventArgs e)
{
a_autor autor = new a_autor();
autor.at_id = id.Text;
autor.at_vorname = vorname.Text;
autor.at_nachname = nachname.Text;
autor.at_gebDatum = Convert.ToDateTime(datum.Text);
_sourceCollection.Add(autor);
db.a_autor.Add(autor);
box.Items.Refresh();
}
You can create an ObservableCollection instead of binding to the List. ObservableCollection implements INotifyPropertyChanged so it can send a notification whenever something is changed in the container.
Also, I would suggest you to try
public void RefreshListBox()
{
box.ItemsSource =
(from m in db.a_autor
orderby m.at_id
select m).ToList();
}
and call this after db.SaveChanges()
You should use MVVM pattern instead of code behind and use property changes. First result in Google:
https://www.codeproject.com/Articles/819294/WPF-MVVM-step-by-step-Basics-to-Advance-Level
I hope it helps you.
Juan

MVVM light Binding Path not working

I'm trying to bind a variable to show in a label's content.
I use Galasoft's MVVM light to achieve this.
I send my viewmodel, my window and my window.cs. The issue is that nothing happens when I increase the values but something should.
Window: I have binding on only one label
<Window x:Class="DPCKOU_prog3hf_pong.Settings"
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:DPCKOU_prog3hf_pong"
mc:Ignorable="d"
Title="Settings" Height="406" Width="717"
Background="{StaticResource MainMenuBG}"
ResizeMode="NoResize"
WindowStartupLocation="CenterScreen"
>
<Grid>
<StackPanel>
<Label x:Name="Title" HorizontalContentAlignment="Center" HorizontalAlignment="Stretch"
Foreground="#00e4ff" FontSize ="28" Content="Size of pad"
Margin="10,30,10,10">
<Label.BitmapEffect>
<DropShadowBitmapEffect Color="#00e4ff" ShadowDepth="0" Opacity="1"/>
</Label.BitmapEffect>
</Label>
<Label x:Name="Size" HorizontalContentAlignment="Center" HorizontalAlignment="Stretch"
Foreground="#00e4ff" FontSize ="40" Content="{Binding Path=PadSize}"
Margin="10,0,10,10">
<Label.BitmapEffect>
<DropShadowBitmapEffect Color="#00e4ff" ShadowDepth="0" Opacity="1"/>
</Label.BitmapEffect>
</Label>
<DockPanel>
<Button x:Name="Increase" Content="Increase" HorizontalAlignment="Left"
Width="149" Height="46" Foreground="#00e4ff" Background="Black" Margin="120,10,10,10"
FontSize="18" BorderThickness="0" Click="Increase_Click">
<Button.BitmapEffect>
<DropShadowBitmapEffect Color="#00e4ff" ShadowDepth="0" Opacity="1"/>
</Button.BitmapEffect>
</Button>
<Button x:Name="Decrease" Content="Decrease" HorizontalAlignment="Right"
Width="149" Height="46" Foreground="#00e4ff" Background="Black" Margin="10,10,120,10"
FontSize="18" BorderThickness="0" Click="Decrease_Click">
<Button.BitmapEffect>
<DropShadowBitmapEffect Color="#00e4ff" ShadowDepth="0" Opacity="1"/>
</Button.BitmapEffect>
</Button>
</DockPanel>
<Button x:Name="Play" Content="Play" HorizontalAlignment="Center"
Width="149" Height="46" Foreground="#00e4ff" Background="Black" Margin="10,10,10,10"
FontSize="18" BorderThickness="0" Click="Play_Click">
<Button.BitmapEffect>
<DropShadowBitmapEffect Color="#00e4ff" ShadowDepth="0" Opacity="1"/>
</Button.BitmapEffect>
</Button>
<Button x:Name="Back" Content="Back" HorizontalAlignment="Center"
Width="149" Height="46" Foreground="#00e4ff" Background="Black" Margin="10,10,10,10"
FontSize="18" BorderThickness="0" Click="Back_Click">
<Button.BitmapEffect>
<DropShadowBitmapEffect Color="#00e4ff" ShadowDepth="0" Opacity="1"/>
</Button.BitmapEffect>
</Button>
</StackPanel>
</Grid>
The model's cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
namespace DPCKOU_prog3hf_pong
{
class SettingsVM : ViewModelBase
{
int padSize;
public int PadSize
{
get
{
return padSize;
}
set
{
if(value >=1 && value <= 6)
{
Set(ref padSize, value);
}
}
}
public SettingsVM()
{
padSize = 1;
}
}
}
and the window.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using GalaSoft.MvvmLight;
namespace DPCKOU_prog3hf_pong
{
/// <summary>
/// Interaction logic for SingleSettings.xaml
/// </summary>
///
/*
* take it 100 pixels is the 4 units of the pad's size respectively.
* so 25 shall be 1 and that is the default value one can input.
* the player can input pad size from 1 to 6 meaning from 25 pixels to 150.
*/
public partial class Settings : Window
{
/*
* its sole purpose is to change the pad size.
*/
SettingsVM svm;
bool isPlaymodeSingle;
public Settings(bool isPlaymodeSingle)
{
InitializeComponent();
this.isPlaymodeSingle = isPlaymodeSingle;
svm = new SettingsVM();
}
private void Play_Click(object sender, RoutedEventArgs e)
{
if (isPlaymodeSingle)
{
//yes, solo
SinglePlayer spgame = new SinglePlayer();
spgame.Show();
Close();
/*
* show the game window and close this.
*/
}
else
{
//nope, multi.
}
}
private void Decrease_Click(object sender, RoutedEventArgs e)
{
svm.PadSize--;
}
private void Increase_Click(object sender, RoutedEventArgs e)
{
svm.PadSize++;
}
private void Back_Click(object sender, RoutedEventArgs e)
{
MainWindow mw = new MainWindow();
mw.Show();
Close();
}
}
}
You forgot to set the DataContext of the Window.
You can do that for example in the constructor of the Settings class:
public Settings(bool isPlaymodeSingle)
{
InitializeComponent();
this.isPlaymodeSingle = isPlaymodeSingle;
svm = new SettingsVM();
DataContext = svm; // here
}

Add user control on a button click from another user control

i have two user control and when i click on a button from the first user control ,another user control shows up :
The first user control is:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Navigateur.Presentation.UserControlWork
{
/// <summary>
/// Logique d'interaction pour ListeBlanche.xaml
/// </summary>
public partial class ListeBlanche : UserControl
{
public ListeBlanche()
{
InitializeComponent();
}
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
ServiceReferenceParent.ParentServiceClient wcfParent = new ServiceReferenceParent.ParentServiceClient();
bool existe = await wcfParent.LogInAsync(textmail.Text, textpass.Text);
if (existe)
{
//grid.Children.Remove(this);
//this.Visibility = System.Windows.Visibility.Collapsed;
//ParentControl parmain = new ParentControl();
//parmain.Visibility = System.Windows.Visibility.Visible;
//parmain.
}
else
{
Popup1.IsOpen = true;
}
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
MainWindow main = new MainWindow();
ParentControl parmain = new ParentControl();
main.gridMain.Children.Add(parmain);
parmain.Visibility = System.Windows.Visibility.Visible;
this.Visibility = System.Windows.Visibility.Hidden;
}
}
}
and when i click on "Button_Click_2",ParentControl shows up but it never shows.
Fullscreen:
this is the ParenControl xaml code:
`<UserControl x:Class="Navigateur.Presentation.UserControlWork.ParentControl"
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"
mc:Ignorable="d" Width="586.194" Height="316.418">
<Grid Background="#FF65B4EC" ClipToBounds="True">
<Canvas HorizontalAlignment="Left" Height="69" VerticalAlignment="Top" Width="586" Background="#FF5ACAFF" ClipToBounds="True">
<Label Content="Création de votre compte parent" Canvas.Left="188" Canvas.Top="20" RenderTransformOrigin="0.5,0.5" Width="155" Background="#FF65B4EC" FontWeight="Black">
<Label.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="-0.376"/>
<TranslateTransform/>
</TransformGroup>
</Label.RenderTransform>
</Label>
</Canvas>
<Label Content="Nom Compte" HorizontalAlignment="Left" Margin="121,106,0,0" VerticalAlignment="Top"/>
<Label Content="Pseudo" HorizontalAlignment="Left" Margin="323,165,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.498,0.006"/>
<Label Content="Prénom" HorizontalAlignment="Left" Margin="121,219,0,0" VerticalAlignment="Top"/>
<Label Content="Nom" HorizontalAlignment="Left" Margin="323,214,0,0" VerticalAlignment="Top" RenderTransformOrigin="-0.2,0.471"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="121,132,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="335"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="323,191,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="133"/>
<RadioButton Content="Monsieur" HorizontalAlignment="Left" Margin="121,191,0,0" VerticalAlignment="Top" Height="23"/>
<RadioButton Content="Madame" HorizontalAlignment="Left" Margin="192,191,0,0" VerticalAlignment="Top" Height="23"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="121,245,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="131"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="323,245,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="133" RenderTransformOrigin="0.5,0.5"/>
<Button Content="Annuler" HorizontalAlignment="Left" Margin="192,288,0,0" VerticalAlignment="Top" Width="75" Height="23"/>
<Button Content="Suivant" HorizontalAlignment="Left" Margin="297,288,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</UserControl>`
and this is my main window xaml code:
<Window x:Name="wndmain" x:Class="Navigateur.Presentation.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:auth="clr-namespace:Navigateur.Presentation.UserControlWork"
Title="MainWindow" Height="317" Width="586.194" WindowState="Maximized" WindowStyle="None" Topmost="True" ResizeMode="NoResize">
<Grid x:Name="gridMain">
<auth:ListeBlanche ClickedInUserControl="OnClickedInUserControl"></auth:ListeBlanche>
</Grid>
</Window>
I think you need to use a RoutedEvent in your UserControl to get this to work.
So change your click event in your usercontrol to:
public event RoutedEventHandler ClickedInUserControl;
private void Button_Click_2(object sender, RoutedEventArgs e)
{
if (ClickedInUserControl != null)
{
ClickedInUserControl(this, new RoutedEventArgs());
}
}
Then in you MainWindow's xaml add this too the UserControl:
ClickedInUserControl="OnClickedInUserControl"
And then add the event handler on your mainwindow's codebehind
private void OnClickedInUserControl(object sender, RoutedEventArgs e)
{
ParentControl parmain = new ParentControl();
this.gridMain.Children.Add(parmain);
parmain.Visibility = System.Windows.Visibility.Visible;
// also remove the original usercontrol from the grid and collapse it's vilisibilty
}
Also, I would highly recommend that you look into using Commands rather than Events for this kind of thing, but I used events because that's what you were working with.

TextBox input to TextBlock in other page

I'm using c# and WPF web application and I want to build a simple form which contains two text boxes for user input (name and phone number) and a "send" button. when the user clicks on the send button it will redirect to an other page and will display (with textblock) the entered values.
I tried to read about data binding, but still didn't success to make it work.
1. How do I save the entered values into a variable ?
2. How do I call these variables from the second page and display the saved text ?
Hope for help, thanks!
xaml code of the form:
<TextBlock Height="20" Width="120" Margin="36,43,144,237">enter details:</TextBlock>
<TextBlock Height="20" Width="40" Margin="36,69,224,211">Name:</TextBlock>
<TextBlock Height="20" Width="40" Margin="36,103,224,177">Phone:</TextBlock>
<!--textboxes-->
<TextBox Height="20" Width="95" Margin="100,69,104,211" Name="getName" Background="Gray"/>
<TextBox Height="20" Width="95" Margin="100,103,105,177" Name="getPhoneNumber" Background="Gray"/>
<!-- -->
<Button Height="20" Width="50" Margin="218,103,32,177" Name="sendButton" Click="sendButton_Click">send</Button>
what should be the code behind ? i simply want to display the entered values on an other page with textblock.
this is the function i use to redirect to the "result page":
public void sendButton_Click(object sender, RoutedEventArgs e)
{
Submit();
}
void Submit()
{
Page2 resultpage = new Page2();
NavigationService.Navigate(resultpage);
}
Edit:
Ok I succeed to make it work thanks to Mike's answer.
Thanks Mike, for other users this how the code looks like now:
form page xaml code:
<TextBlock Height="20" Width="120" Margin="36,43,144,237">enter details:</TextBlock>
<TextBlock Height="20" Width="40" Margin="36,69,224,211">Name:</TextBlock>
<TextBlock Height="20" Width="40" Margin="36,103,224,177">Phone:</TextBlock>
<!--textboxes-->
<TextBox Height="20" Width="95" Margin="100,69,104,211" Name="getName" Background="Gray"/>
<TextBox Height="20" Width="95" Margin="100,103,105,177" Name="getPhoneNumber" Background="Gray"/>
<!-- -->
<Button Height="20" Width="50" Margin="218,103,32,177" Name="sendButton" Click="sendButton_Click">send</Button>
form page c# behind code:
public partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
}
public void sendButton_Click(object sender, RoutedEventArgs e)
{
Submit();
}
void Submit()
{
Page2 resultpage = new Page2(getName.Text, getPhoneNumber.Text);
NavigationService.Navigate(resultpage);
}
}
result page xaml code:
<Grid>
<TextBlock x:Name="showName" Height="50" Width="100" Margin="65,125,73,125" Text="{Binding ElementName=showName, Path=Text}" />
</Grid>
result page c# code behind:
public Page2(string name, string phoneNumber)
{
InitializeComponent();
showName.Text = name;
}
Thanks again Mike :)
Ok here is what I would do. You can create arguments in the constructor of your Page2:
public Page2(string name, string phoneNumber)
{
//login to handle name and phone number
}
On your first page you can just pass name and phone number using the Name property in the xaml.
void Submit()
{
Page2 resultpage = new Page2(getName.Text, getPhoneNumber.Text);
NavigationService.Navigate(resultpage);
}
<Page x:Class="Login.Page1" 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"
mc:Ignorable="d"
d:DesignHeight="253" d:DesignWidth="276"
Title="Page1" Background="Blue">
<Grid>
<TextBlock Text="Prince jain" HorizontalAlignment="Left" VerticalAlignment="Top" Height="50" Width="100" Margin="48,0,0,0" FontSize="40"></TextBlock>
<TextBlock Height="50" FontSize="18" HorizontalAlignment="Left" Margin="6,141,0,0" Name="txtnavigatevalue" Text="Test Navigation" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="134,144,0,0" Name="txtnavigation" VerticalAlignment="Top" Width="130" />
<Button Content="Check" Height="23" HorizontalAlignment="Left" Margin="134,187,0,0" Name="buttoncheck" VerticalAlignment="Top" Width="75" Click="buttoncheck_Click" />
</Grid>
</Page>
<Page x:Class="Login.Page2"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="Page2" Background="BlueViolet">
<Grid>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="46,94,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" Width="198" />
</Grid>
</Page>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Login
{
/// <summary>
/// Interaction logic for Page1.xaml
/// </summary>
public partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
}
private void buttoncheck_Click(object sender, RoutedEventArgs e)
{
Page2 p2 = new Page2();
p2.textBlock1.Text = txtnavigation.Text;
//txtnavigatevalue.Text = "";
NavigationService.Navigate(p2);
}
}
}
private void buttoncheck_Click(object sender, RoutedEventArgs e)
{
Page2 p2 = new Page2();
p2.textBlock1.Text = txtnavigation.Text;
//txtnavigatevalue.Text = "";
NavigationService.Navigate(p2);
}

WPF bind slider's mouseposition value to textblock

I have a slider with minimum 0 and max 100.
I have a popup window that is visible when I mouseover the slider.
Currently, I binded the popup with the slider value.
What I want is:
When I move the mouse over the slider, I want to see value that suppose to be in that position.
For example:
My XAML:
<Window x:Class="WPFMavka.VideoPlayer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFMavka"
Title="MainWindow" WindowStyle="None" Width="1920" Height="1080" WindowState="Maximized" KeyboardNavigation.TabNavigation="None" Closing="Window_Closing">
<Grid Name="tst">
<local:MetroSlider x:Name="bla" MouseMove="Rectangle_MouseMove" MouseLeave="Rectangle_MouseLeave" IsMoveToPointEnabled="True" HorizontalAlignment="Left" Width="542" VerticalAlignment="Top" Margin="116,839,0,0" Value="0" Style="{DynamicResource SliderStyle1}" Height="66" AutoToolTipPrecision="0" AutoToolTipPlacement="TopLeft"/>
<Popup Name="floatingTip" AllowsTransparency="True" Placement="Relative" PlacementTarget="{Binding ElementName=bla}">
<Border BorderBrush="Black" BorderThickness="1" Padding="4">
<TextBlock Text="{Binding ElementName=bla, Path=Value}"></TextBlock>
</Border>
</Popup>
</Grid>
</Window>
My Code-Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WPFMavka
{
/// <summary>
/// Interaction logic for VideoPlayer.xaml
/// </summary>
public partial class VideoPlayer : Window
{
public VideoPlayer()
{
InitializeComponent();
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Environment.Exit(1);
}
private void Rectangle_MouseMove(object sender, MouseEventArgs e)
{
if (!floatingTip.IsOpen) { floatingTip.IsOpen = true; }
Point currentPos = e.GetPosition(bla);
floatingTip.HorizontalOffset = currentPos.X-14;
floatingTip.VerticalOffset = -32;
}
private void Rectangle_MouseLeave(object sender, MouseEventArgs e)
{
floatingTip.IsOpen = false;
}
}
}
Found a better solution - changing the TextBlock onMouseOver the slide > I get the current position of mouse on the slider and then uses .ValueFromPoint()
XAML:
<Window x:Class="WPFMavka.VideoPlayer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFMavka"
Title="MainWindow" WindowStyle="None" Width="1920" Height="1080" WindowState="Maximized" KeyboardNavigation.TabNavigation="None" Closing="Window_Closing">
<Grid Name="tst">
<local:MetroSlider x:Name="slider" MouseMove="slider_MouseMove" MouseLeave="slider_MouseLeave" IsMoveToPointEnabled="True" HorizontalAlignment="Left" Width="746" VerticalAlignment="Top" Margin="330,851,0,0" Value="0" Style="{DynamicResource SliderStyle1}" Height="44"/>
<Popup Name="floatingTip" AllowsTransparency="True" Placement="Relative" PlacementTarget="{Binding ElementName=slider}">
<Border Name="floatingTipBorder" BorderBrush="Black" BorderThickness="1" Padding="4">
<TextBlock Name="sliderTextBlock"/>
</Border>
</Popup>
</Grid>
</Window>
Code-Behind:
private void slider_MouseMove(object sender, MouseEventArgs e)
{
if (!floatingTip.IsOpen) { floatingTip.IsOpen = true; }
Point currentPos = e.GetPosition(slider);
Track _track = slider.Template.FindName("PART_Track", slider) as Track;
sliderTextBlock.Text = _track.ValueFromPoint(currentPos).ToString();
floatingTip.HorizontalOffset = currentPos.X -(floatingTipBorder.ActualWidth / 2);
floatingTip.VerticalOffset = -32;
}
private void slider_MouseLeave(object sender, MouseEventArgs e)
{
floatingTip.IsOpen = false;
}
You can use AttachedCommands for this. You can download the library from here. So in this case you could do something like:
<Window x:Class="WPFMavka.VideoPlayer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFMavka"
xmlns:AttachedCommand="clr-namespace:AttachedCommandBehavior;assembly=AttachedCommandBehavior"
Title="MainWindow"
WindowStyle="None"
Width="1920"
Height="1080"
WindowState="Maximized"
KeyboardNavigation.TabNavigation="None"
Closing="Window_Closing">
<Grid Name="tst">
<local:MetroSlider x:Name="bla"
MouseMove="Rectangle_MouseMove"
MouseLeave="Rectangle_MouseLeave"
IsMoveToPointEnabled="True"
HorizontalAlignment="Left"
Width="542" VerticalAlignment="Top"
Margin="116,839,0,0"
Value="0"
Style="{DynamicResource SliderStyle1}"
Height="66" AutoToolTipPrecision="0"
AutoToolTipPlacement="TopLeft"
AttachedCommand:CommandBehavior.Event="MouseMove"
AttachedCommand:CommandBehavior.Command="{Binding UpdateCurrentMouseTimeCommand}"
AttachedCommand:CommandBehavior.CommandParameter="{Binding ElementName=Bla, Path=Value}"/>
<Popup Name="floatingTip" AllowsTransparency="True"
Placement="Relative"
PlacementTarget="{Binding ElementName=bla}">
<Border BorderBrush="Black" BorderThickness="1" Padding="4">
<TextBlock Text="{Binding CurrentMouseTime, NotifyOnSourceUpdated=True, Mode=OneWay}" />
</Border>
</Popup>
</Grid>
</Window>
Then in your command UpdateCurrentMouseTimeCommand you set the property
private string currentMouseTime = String.Empty;
public string CurrentMouseTime
{
get { return value; }
set
{
if (currentMouseTime == value)
return;
currentMouseTime = value;
OnPropertyChanged("CurrentMouseTime");
}
}
Where the containing class must implement INotifyPropertyChanged.
I hope this helps.

Categories