passing values between two pages wpf - c#

I am learning c# and I have been asked to work on a project using WPF, which I don't know much. We are using MUI as well.
I am trying to achieve a pretty basic task. I have two pages called ClientRNG.xamland ServerRNG.xaml. In ClientRNG.xaml I have two buttons and two textfield, when each button is pressed a random number is generated and it appears in a text box. In ServerRNG there are just one button and one textfield, with the same functionality as mentioned above.
So I'll end up with three different random numbers, one in ServerRNG.xaml and two in ClientRNG.
What i want to do is to pass these random numbers to another page called SSL.xaml.
The pages are created in MainWindow.xml:
<mui:ModernWindow.MenuLinkGroups>
<mui:LinkGroup DisplayName="network security">
<mui:LinkGroup.Links>
<mui:Link DisplayName="Home" Source="/Pages/Home.xaml" />
<mui:Link DisplayName="RNG" Source="/Pages/ClientRNG.xaml" />
<mui:Link DisplayName="3DES" Source="/Pages/3des.xaml" />
<mui:Link DisplayName="RSA" Source="/Pages/RSA.xaml" />
<mui:Link DisplayName="SHA-1" Source="/Pages/sha1.xaml" />
<mui:Link DisplayName="PKI Certificates" Source="/Pages/pki.xaml" />
<mui:Link DisplayName="SSL" Source="/Pages/SSL.xaml" />
</mui:LinkGroup.Links>
</mui:LinkGroup>
<mui:LinkGroup DisplayName="settings" GroupName="settings">
<mui:LinkGroup.Links>
<mui:Link DisplayName="software" Source="/Pages/Settings.xaml" />
</mui:LinkGroup.Links>
</mui:LinkGroup>
</mui:ModernWindow.MenuLinkGroups>
<mui:ModernWindow.TitleLinks>
<mui:Link DisplayName="settings" Source="/Pages/Settings.xaml" />
</mui:ModernWindow.TitleLinks>
Code in ClientRNG:
namespace NetworkSecuritySSLTest.Pages
{
/// <summary>
/// Interaction logic for RNG.xaml
/// </summary>
public partial class ClientRNG : UserControl
{
public ClientRNG()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Random r = new Random(1);
int number = r.Next(0, 100);
r1Out.Text = number.ToString();
SharingManager.GlobalValue = number;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Random r = new Random(3);
int number = r.Next(0, 100);
pmsOutC.Text = number.ToString();
}
here is the code I have in ServerRNG:
namespace NetworkSecuritySSLTest.Pages
{
/// <summary>
/// Interaction logic for RNG.xaml
/// </summary>
public partial class ServerRNG : UserControl
{
private SplitPage1 sp;
public ServerRNG()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Random r = new Random(2);
int number = r.Next(0, 100);
r2Out.Text = number.ToString();
SharingManager.GlobalValue = number;
}
}
}
and this is the code behind SSL class
namespace NetworkSecuritySSLTest.Pages
{
/// <summary>
/// Interaction logic for SplitPage1.xaml
/// </summary>
public partial class SplitPage1 : UserControl
{
private int r1FromClient;
public SplitPage1()
{
InitializeComponent();
SharingManager.ValueChanged += UpdateTextBox1;
SharingManager.ValueChanged += UpdateTextBox2;
}
public void UpdateTextBox1(object sender, NumericEventArgs e)
{
r1SSLBox.Text = e.Value.ToString(); // Update textBox
}
public void UpdateTextBox2(object sender, NumericEventArgs e)
{
r2SSLBox.Text = e.Value.ToString(); // Update textBox
}
}
}
here are the xaml:
'SplitPage1'
<UserControl x:Class="NetworkSecuritySSLTest.Pages.SplitPage1"
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:mui="http://firstfloorsoftware.com/ModernUI"
mc:Ignorable="d"
d:DesignWidth="766.507" Height="535">
<Grid Style="{StaticResource ContentRoot}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="6"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ScrollViewer>
<StackPanel>
<TextBlock Text="CLIENT" Style="{StaticResource Heading2}" />
<TextBlock x:Name="hello" Text="Hello Server. This is my Random Number and my Security Capabilities:" FontSize="12" FontStyle="Italic" Margin="0,10,0,0" UseLayoutRounding="False" TextWrapping="Wrap" />
<TextBlock x:Name="helloCont" Text="" FontSize="12" FontStyle="Italic" Margin="0,0,0,0" />
<TextBox x:Name ="r1SSLBox" HorizontalAlignment="Left" Height="57" Margin="10,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.498,0.404"/>
<TextBox x:Name ="r2SSLBox" HorizontalAlignment="Left" Height="57" Margin="10,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.498,0.404"/>
<TextBlock x:Name="VerifyDC" Text="I need to verify your Digital Certificate:" FontSize="12" FontStyle="Italic" Margin="0,10,0,0" />
<TextBlock x:Name="VerifyCont" Text="" FontSize="12" FontStyle="Italic" />
<TextBlock x:Name="MSK" Text="My Master Key is:" FontSize="12" FontStyle="Italic" Margin="0,10,0,0" />
<TextBlock x:Name="MSKCont" Text="" FontSize="12" FontStyle="Italic" />
</StackPanel>
</ScrollViewer>
<GridSplitter Grid.Column="1" />
<ScrollViewer Grid.Column="2 " Margin="{StaticResource SplitRight}">
<StackPanel>
<TextBlock Text="SERVER" Style="{StaticResource Heading2}" />
<TextBlock Text="Content goes here" />
</StackPanel>
</ScrollViewer>
<GridSplitter Grid.ColumnSpan="3" HorizontalAlignment="Left" Margin="0,23,0,0" VerticalAlignment="Top" Width="735"/>
<Button Content="Man-In-The-Middle-Attack" HorizontalAlignment="Left" VerticalAlignment="Top" Width="209" RenderTransformOrigin="0.055,0.397" Height="40" Margin="255,451,0,0" Grid.ColumnSpan="3" />
</Grid>
ClientRNG
<UserControl x:Class="NetworkSecuritySSLTest.Pages.ClientRNG"
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:mui="http://firstfloorsoftware.com/ModernUI"
mc:Ignorable="d"
d:DesignWidth="766.507" Height="535">
<Viewbox Stretch="None">
<Grid Style="{StaticResource ContentRoot}" Height="301" Margin="0" Width="435">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions>
<!-- TODO: set #SelectedSource -->
<mui:ModernTab Layout="Tab" Margin="0,52,0,0">
<mui:ModernTab.Links>
<!-- TODO: set #Source -->
<mui:Link DisplayName="Client" />
<mui:Link DisplayName="Server" Source="/Pages/ServerRNG.xaml" />
</mui:ModernTab.Links>
</mui:ModernTab>
<Button Content="GENERATE R# 1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.055,0.397" Height="26" Margin="10,52,0,0" FontSize="11" Click="Button_Click" />
<TextBox Name ="r1Out" HorizontalAlignment="Left" Height="57" Margin="10,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.498,0.404"/>
<Button Content="GENERATE MS" HorizontalAlignment="Left" VerticalAlignment="Top" Width="119" RenderTransformOrigin="0.055,0.397" Height="26" Margin="306,52,0,0" Click="Button_Click_2" />
<TextBox Name ="msOutC" HorizontalAlignment="Left" Height="57" Margin="306,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="119" RenderTransformOrigin="0.498,0.404"/>
<Button Content="GENERATE PMS" HorizontalAlignment="Left" VerticalAlignment="Top" Width="133" RenderTransformOrigin="0.055,0.397" Height="26" Margin="151,52,0,0" Click="Button_Click_1" />
<TextBox Name ="pmsOutC" HorizontalAlignment="Left" Height="57" Margin="151,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="133" RenderTransformOrigin="0.498,0.404"/>
<Label Content="Random Number Generator" HorizontalAlignment="Left" Height="19" Margin="10,10,0,0" VerticalAlignment="Top" Width="415" FontWeight="Bold"/>
</Grid>
</Viewbox>
and ServerRNG
<UserControl x:Class="NetworkSecuritySSLTest.Pages.ServerRNG"
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:mui="http://firstfloorsoftware.com/ModernUI"
mc:Ignorable="d"
d:DesignWidth="766.507" Height="535">
<Viewbox Stretch="None">
<Grid Style="{StaticResource ContentRoot}" Height="301" Margin="0" Width="435">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions>
<!-- TODO: set #SelectedSource -->
<mui:ModernTab Layout="Tab" Margin="0,52,0,0">
<mui:ModernTab.Links>
<!-- TODO: set #Source -->
<mui:Link DisplayName="Client" Source="/Pages/ClientRNG.xaml" />
<mui:Link DisplayName="Server" />
</mui:ModernTab.Links>
</mui:ModernTab>
<Button Name ="r2but" Content="GENERATE R# 2" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.055,0.397" Height="26" Margin="76,52,0,0" FontSize="11" Click="Button_Click_1" />
<TextBox Name ="r2Out" HorizontalAlignment="Left" Height="57" Margin="76,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.498,0.404"/>
<Button Content="GENERATE MS" HorizontalAlignment="Left" VerticalAlignment="Top" Width="119" RenderTransformOrigin="0.055,0.397" Height="26" Margin="249,52,0,0" />
<TextBox Name ="msOutS" HorizontalAlignment="Left" Height="57" Margin="249,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="119" RenderTransformOrigin="0.498,0.404"/>
<Label Content="Random Number Generator" HorizontalAlignment="Left" Height="19" Margin="10,10,0,0" VerticalAlignment="Top" Width="415" FontWeight="Bold"/>
</Grid>
</Viewbox>
Now I was trying to use the solution posted by Omribitan but i am still struggling

According to what you said in the comment section that SplitPage1 is already shown,
What you are doing in your code is creating a new instance of SplitPage1 and passing it your data
SplitPage1 sp = new SplitPage1(); // This is a new page, not the one currently shown in your application
sp.Setr1SSLBox(number); // it should set the text box in SSL page
So if you want to set the text of the currently displayed SplitPage1, you need to get it's reference. It's hard to say how because I can't see your entire code but this is what I would consider:
Using IoC container to resolve the current instance of SplitPage1.
According to your code seems like there is a third party creating these pages. If that's true, it could pass ServerRNG a reference of the SplitPage1 it's creating which you'll be able to use later, for example :
public partial class ServerRNG : UserControl
{
private SplitPage1 sp;
public ServerRNG(SplitPage1 splitPage) : this()
{
sp = splitPage; // Save a reference to the currently displayed `SplitPage1` page
}
public ServerRNG()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Random r = new Random(2);
int number = r.Next(0, 100);
r2Out.Text = number.ToString();
sp.Setr1SSLBox(number); // Set the correct instance's text
}
}
Create a class which will expose a static property and event that will fire when that property changes:
public class SharingManager
{
// Define a global static event to be fired when the value is changing
public static event EventHandler<NumericEventArgs> ValueChanged;
public static int GlobalValue
{
set
{
// Fire ValueChanged event
if (ValueChanged != null)
ValueChanged(null, new NumericEventArgs(value));
}
}
}
public class NumericEventArgs : EventArgs
{
public NumericEventArgs(int value)
{
Value = value;
}
public int Value { get; set; }
}
Register a handler in SplitPage1
public SplitPage1()
{
InitializeComponent();
SharingManager.ValueChanged += UpdateTextBox;
}
public void UpdateTextBox(object sender, NumericEventArgs e)
{
r1SSLBox.Text = e.Value.ToString(); // Update textBox
}
In Button_Click_1 on ServerNRG, update the value to fire the event
Random r = new Random(2);
int number = r.Next(0, 100);
r2Out.Text = number.ToString();
SharingManager.GlobalValue = number;
Hope this helps

you should work on WPF using the MVVM design pattern.
Its kinda annoying without MVVM framework
I suggest you to use http://caliburnmicro.codeplex.com/
use this tutorial to get started
http://www.mindscapehq.com/blog/index.php/2012/01/12/caliburn-micro-part-1-getting-started/
it also explains how to use the mediator pattern (using caliburn micros event aggerator) to pass values/commands between diffrent windows.
http://www.mindscapehq.com/blog/index.php/2012/2/1/caliburn-micro-part-4-the-event-aggregator/

Related

not set component in model

I need to insert data from usercontrol into database.
I tried to set xml component into my model but it results in System.NullReferenceException.
Where is the problem ? How can I solve this?
usercontrol.cs:
public partial class League : UserControl
{
private Leagues _leagueVM;
public Leagues LeagueVM
{
get
{
_leagueVM.EnLeagueName = txtLeagueNameEN.Text;
_leagueVM.FaLeagueName = txtLeagueNameFA.Text;
_leagueVM.LeagueLogo = imgLogoLeague.Name;
return _leagueVM;
}
set
{
txtLeagueNameEN.Text = _leagueVM.EnLeagueName;
txtLeagueNameFA.Text = _leagueVM.FaLeagueName;
imgLogoLeague.Name = _leagueVM.LeagueLogo;
}
}
public League()
{
var leagueManager = Inject.Container.GetInstance<ILeagueService>();
InitializeComponent();
}
private void Image_MouseDown(object sender, MouseButtonEventArgs e)
{
FileDialog dialog = new OpenFileDialog();
dialog.ShowDialog();
}
private void btnInsertLeague_Click(object sender, RoutedEventArgs e)
{
var leagueManager = Inject.Container.GetInstance<ILeagueService>();
leagueManager.Add(LeagueVM);
}
}
xml:
<UserControl x:Class="Bet.UControl.UControls.League"
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:Bet.UControl.UControls"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800" Width="1255" Height="624">
<Grid Margin="10,0,10,10">
<GroupBox Header="New League" Background="#fff" HorizontalAlignment="Center" Height="151" Margin="10,10,0,0" VerticalAlignment="Top" Width="1215">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<Label Content="LeagueName (En) : " Foreground="Black" Width="111" FontFamily="Rockwell" Height="28"/>
<TextBox x:Name="txtLeagueNameEN" Width="199" Height="30" Margin="10,20,30,40" />
<Label Content="LeagueName (En) : " Foreground="Black" Width="111" FontFamily="Rockwell" Height="28"/>
<TextBox x:Name="txtLeagueNameFA" Width="199" Height="30" Margin="10,20,30,40" />
<Label Content="League Logo " Foreground="Black" Width="111" FontFamily="Rockwell" Height="28"/>
<Image x:Name="imgLogoLeague" Width="90" Height="85" Margin="5,0,0,0" Source="E:\MyProject\Bet\Bet\Assetes\adfg.png" MouseDown="Image_MouseDown"/>
<Button x:Name="btnInsertLeague" Content="Add" Height="Auto" Width="75" Margin="100,27,30,43" Click="btnInsertLeague_Click"/>
</StackPanel>
</GroupBox>
<DataGrid HorizontalAlignment="Left" Height="420" Margin="15,184,0,0" VerticalAlignment="Top" Width="1210"/>
</Grid>
It seems you missed to create a Leagues object and assign it to _leagueVM.
Should be easy to see if you use the debugger.

Creating a new instance of a window I have created. Called multiple times to do different things

I have created a window which is a numbered keypad :
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Name="btnTotal" Width="280" Height="60" Grid.ColumnSpan="3" Grid.Row="0" Margin="10,10,10,10" Background="#302F37" Foreground="AntiqueWhite" FontSize="35"></TextBox>
<Button x:Name="btnZzero" Content="0" Width="80" Height="60" Grid.Column="0" Grid.Row="4" Margin="5,5,5,5" Background="#302F37" Foreground="White" Focusable="False" Click="btnZzero_Click"></Button>
<Button x:Name="btnOk" Content="OK" Width="80" Height="60" Grid.Column="1" Grid.Row="4" Margin="5,5,5,5" Click="btnOk_Click" Background="#FF8FC377" Focusable="False"></Button>
<Button x:Name="btnCancel" Content="Cancel" Width="80" Height="60" Grid.Column="2" Grid.Row="4" Margin="5,5,5,5" Click="cancel_Click" BorderBrush="Black" Background="#FFD64D4D" Focusable="False"></Button>
<Button x:Name="btnOne" Content="1" Width="80" Height="60" Grid.Column="0" Grid.Row="3" Margin="14,6,0,6" Focusable="False" Background="#302F37" Foreground="White" HorizontalAlignment="Left" Click="btnOne_Click"></Button>
<Button x:Name="btnTwo" Content="2" Width="80" Height="60" Grid.Column="1" Grid.Row="3" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White" Click="btnTwo_Click"/>
<Button x:Name="btnThree" Content="3" Width="80" Height="60" Grid.Column="2" Grid.Row="3" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"/>
<Button x:Name="btnFour" Content="4" Width="80" Height="60" Grid.Column="0" Grid.Row="2" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"></Button>
<Button x:Name="btnFive" Content="5" Width="80" Height="60" Grid.Column="1" Grid.Row="2" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"></Button>
<Button x:Name="btnSix" Content="6" Width="80" Height="60" Grid.Column="2" Grid.Row="2" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"></Button>
<Button x:Name="btnSeven" Content="7" Width="80" Height="60" Grid.Column="0" Grid.Row="1" Margin="12,5,9,6" Focusable="False" Background="#302F37" Foreground="White"></Button>
<Button x:Name="btnEight" Content="8" Width="80" Height="60" Grid.Column="1" Grid.Row="1" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"></Button>
<Button x:Name="btnNine" Content="9" Width="80" Height="60" Grid.Column="2" Grid.Row="1" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"></Button>
Now, I would like to call this keypad at different times in my application to do different things.
IE I want to use it for a login screen :
<Window x:Class="WpfApplication2.MainLogin2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainLogin2" WindowState="Maximized" Width="1024" Height="768" WindowStyle="None" WindowStartupLocation="CenterScreen">
<Grid Background="#FF260538">
<Grid.RowDefinitions>
<RowDefinition Height="768" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1024" />
</Grid.ColumnDefinitions>
<TextBox Name="userIDTextBox" HorizontalAlignment="Left" Height="47" Margin="402,249,0,0" TextWrapping="Wrap" Text="User ID" VerticalAlignment="Top" Width="213" FontSize="30" PreviewMouseDown="userIDTextBox_PreviewMouseDown" />
<TextBox Name="passcodeTextBox" Height="47" Margin="402,317,0,0" TextWrapping="Wrap" Text="Passcode" VerticalAlignment="Top" Width="213" FontSize="30" HorizontalAlignment="Left" PreviewMouseDown="passcodeTextBox_PreviewMouseDown" />
<Button Content="OK" HorizontalAlignment="Left" Margin="402,386,0,0" VerticalAlignment="Top" Width="213" Height="59" FontSize="30" Click="okButton_Click"/>
<Button Content="CANCEL" HorizontalAlignment="Left" Margin="402,450,0,0" VerticalAlignment="Top" Width="213" Height="59" FontSize="30" Click="cancelButton_Click_1"/>
</Grid>
My problem is how do I pass the result from the keypad back to different text fields after I have clicked ok?
Here is the code behind the keypad window. I only have the number 1 working so far for testing:
namespace WpfApplication2
{
public partial class QuantityKeypad : Window
{
bool btnClicked = false;
string quantityResult = "";
public QuantityKeypad()
{
InitializeComponent();
}
private void cancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnZzero_Click(object sender, RoutedEventArgs e)
{
}
private void btnOne_Click(object sender, RoutedEventArgs e)
{
if (btnClicked == true)
{
btnTotal.Text = "";
btnClicked = false;
}
quantityResult = quantityResult += "1";
btnTotal.Text = quantityResult;
}
private void btnTwo_Click(object sender, RoutedEventArgs e)
{
}
}
}
And here is the code for the login screen :
namespace WpfApplication2
{
public partial class MainLogin2 : Window
{
public MainLogin2()
{
InitializeComponent();
}
//OK button
private void okButton_Click(object sender, RoutedEventArgs e)
{
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
this.Close();
}
//Cancel button - takes user back to login screen
private void cancelButton_Click_1(object sender, RoutedEventArgs e)
{
this.Close();
}
//Removes text from login textboxes when clicked in
//opens instance of Quantitykeypad when clicking inside textbox
private void userIDTextBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
userIDTextBox.Text = "";
QuantityKeypad loginKeypad = new QuantityKeypad();
loginKeypad.Owner = this;
loginKeypad.ShowDialog();
}
//Removes text from passcode textboxe when clicked in
//opens instance of Quantitykeypad when clicking inside passcode textbox
private void passcodeTextBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
passcodeTextBox.Text = "";
QuantityKeypad loginKeypad = new QuantityKeypad();
loginKeypad.Owner = this;
loginKeypad.ShowDialog();
}
}
}
Terribly sorry if this is simple but I have been struggling for days now.
Thanks
You can make your private field quantityResult a publicly accessible property instead:
public string QuantityResult { get; private set; }
That way, you can read from it:
passcodeTextBox.Text = "";
QuantityKeypad loginKeypad = new QuantityKeypad();
loginKeypad.Owner = this;
loginKeypad.ShowDialog();
passcodeTextBox.Text = loginKeypad.QuantityResult;

ListBox SelectionChanged only once?

I have a ListBox which I add items to. Each time i select an item which is an object of a Person this person properties should be showed in textboxes. This person have person properties like age, name, sex and so on.
my listbox selection changed event only triggers one time or on new added items. It doesn't trigger when i click and an that is not just added.
Mainwindow.xaml.cs
namespace GUI_WPF_Eksamen
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Backlog bl = new Backlog();
public MainWindow()
{
InitializeComponent();
DataContext = bl;
this.PriorityComboBox.Items.Add("High");
this.PriorityComboBox.Items.Add("Medium");
this.PriorityComboBox.Items.Add("Low");
}
private void AddToProductBackLogBtn_Click(object sender, RoutedEventArgs e)
{
this.ProductBacklogList.Items.Add(bl);
this.NameTextBox.Text = String.Empty;
}
private void ProductBacklogList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = this.ProductBacklogList.SelectedItem as Backlog;
this.NameLabel.Content = item.NAME;
this.DescriptionTextBlock.Text = item.DESCRIPTION;
this.PriorityLabel.Content = item.PRIORITY;
this.TimeLabel.Content = item.TIME;
}
private void AddToSprint_Click(object sender, RoutedEventArgs e)
{
var currentItem = this.ProductBacklogList.SelectedItem as Backlog;
this.SprintBacklogList.Items.Add(currentItem);
}
}
}
Mainwindow.xaml
<Window x:Class="GUI_WPF_Eksamen.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:GUI_WPF_Eksamen"
Title="GUI WPF application" Height="800" Width="1200">
<Window.Background>
<ImageBrush ImageSource="Images/chalkboard.jpg"/>
</Window.Background>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="69*"/>
<RowDefinition Height="700*"/>
</Grid.RowDefinitions>
<Label x:Name="Title" Content="SCRUM-BOARD XXL" HorizontalAlignment="Center" HorizontalContentAlignment="Center" Margin="15,10,5,0" VerticalAlignment="Top" Width="1172" Height="56" FontSize="36" FontStyle="Italic" FontWeight="Bold" Foreground="White"/>
<Grid HorizontalAlignment="Left" Height="680" Margin="15,10,0,0" Grid.Row="1" VerticalAlignment="Top" Width="354">
<Grid.RowDefinitions>
<RowDefinition Height="94*"/>
<RowDefinition Height="44*"/>
<RowDefinition Height="131*"/>
<RowDefinition Height="53*"/>
<RowDefinition Height="40*"/>
<RowDefinition Height="46*"/>
<RowDefinition Height="272*"/>
</Grid.RowDefinitions>
<Label Content="Navn" HorizontalAlignment="Left" Margin="0,44,0,0" VerticalAlignment="Top" Width="77" FontSize="16" Foreground="White"/>
<Label Content="Beskrivelse
" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Foreground="White" FontSize="16" Height="31" Grid.Row="1"/>
<Label Content="Prioritet" HorizontalAlignment="Left" Margin="0,7,0,0" VerticalAlignment="Top" Width="67" FontSize="16" Foreground="White" Grid.Row="3"/>
<Label Content="Estimeret tidsforbrug" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Foreground="White" FontSize="16" Grid.Row="4" Grid.RowSpan="2"/>
<TextBox x:Name="NameTextBox" HorizontalAlignment="Left" Height="23" Margin="51,52,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="303" Opacity="0.5" Text="{Binding Path=NAME}"/>
<ComboBox x:Name="PriorityComboBox" HorizontalAlignment="Left" Margin="73,12,0,0" VerticalAlignment="Top" Width="152" RenderTransformOrigin="0.5,0.5" Opacity="0.5" Grid.Row="3" SelectedItem="{Binding Path=PRIORITY}">
<ComboBox.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="0.036"/>
<TranslateTransform/>
</TransformGroup>
</ComboBox.RenderTransform>
</ComboBox>
<TextBox x:Name="TimeTextBox" HorizontalAlignment="Left" Height="23" Margin="0,6,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="204" Opacity="0.5" Grid.Row="5" Text="{Binding Path=TIME}"/>
<Label Content="time(r)" HorizontalAlignment="Left" Margin="209,38,0,0" VerticalAlignment="Top" Foreground="White" FontSize="16" Width="57" Grid.Row="4" Grid.RowSpan="2"/>
<TextBox x:Name="DescriptionTextBox" HorizontalAlignment="Left" Height="111" Margin="0,10,0,0" Grid.Row="2" TextWrapping="Wrap" VerticalAlignment="Top" Width="354" Opacity="0.5" Text="{Binding Path=DESCRIPTION}"/>
<Button x:Name="AddToProductBackLogBtn" Content="Add Backlog item" HorizontalAlignment="Left" Grid.Row="6" VerticalAlignment="Top" Width="200" Height="27" Margin="66,0,0,0" Background="White" Opacity="0.7" Click="AddToProductBackLogBtn_Click"/>
</Grid>
<Grid HorizontalAlignment="Left" Height="680" Margin="374,10,0,0" Grid.Row="1" VerticalAlignment="Top" Width="808" RenderTransformOrigin="0.459,0.431">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="79*"/>
<ColumnDefinition Width="47*"/>
<ColumnDefinition Width="76*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="209*"/>
<RowDefinition Height="131*"/>
</Grid.RowDefinitions>
<Label Content="Navn" HorizontalAlignment="Left" Margin="10,10,0,0" Grid.Row="1" VerticalAlignment="Top" FontSize="16" Foreground="White" Height="31" Width="47"/>
<Label Content="Beskrivelse" HorizontalAlignment="Left" Margin="10,55,0,0" Grid.Row="1" VerticalAlignment="Top" Foreground="White" FontSize="16" Height="31" Width="87"/>
<Label Content="Prioritet
" HorizontalAlignment="Left" Margin="10,10,0,0" Grid.Row="1" VerticalAlignment="Top" Foreground="White" FontSize="16" Height="32" Grid.Column="1" Width="66"/>
<Label Content="Estimeret tidsforbrug" Grid.Column="1" HorizontalAlignment="Left" Margin="10,55,0,0" Grid.Row="1" VerticalAlignment="Top" Foreground="White" FontSize="16" Height="31" Width="159"/>
<Label x:Name="PriorityLabel" Content="" Grid.Column="1" HorizontalAlignment="Left" Margin="90,10,0,0" Grid.Row="1" VerticalAlignment="Top" FontSize="16" Foreground="White" Width="79" Height="31"/>
<Label x:Name="TimeLabel" Grid.Column="2" HorizontalAlignment="Left" Margin="10,55,0,0" Grid.Row="1" VerticalAlignment="Top" Foreground="White" FontSize="16" Width="208" Height="31"/>
<ListBox x:Name="ProductBacklogList" HorizontalAlignment="Left" Height="353" Margin="10,55,0,0" VerticalAlignment="Top" Width="292" DisplayMemberPath="NAME" Opacity="0.505" SelectionChanged="ProductBacklogList_SelectionChanged" RenderTransformOrigin="0.5,0.5">
<ListBox.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform AngleY="-0.195"/>
<RotateTransform/>
<TranslateTransform Y="-0.497"/>
</TransformGroup>
</ListBox.RenderTransform>
</ListBox>
<ListBox x:Name="SprintBacklogList" HorizontalAlignment="Left" Height="353" Margin="10,55,0,0" VerticalAlignment="Top" Width="284" DisplayMemberPath="NAME" Grid.Column="2" Opacity="0.5"/>
<Label x:Name="NameLabel" HorizontalAlignment="Left" Margin="62,14,0,0" Grid.Row="1" VerticalAlignment="Top" Width="244" Height="27" Content="{Binding Path=NAME}" Foreground="White"/>
<Button x:Name="AddToSprint" Content="Add >>" Grid.Column="1" HorizontalAlignment="Left" Margin="54,201,0,0" VerticalAlignment="Top" Width="75" Height="20" Opacity="0.7" Click="AddToSprint_Click"/>
<TextBlock x:Name="DescriptionTextBlock" HorizontalAlignment="Left" Margin="10,86,0,0" Grid.Row="1" TextWrapping="Wrap" VerticalAlignment="Top" Height="166" Width="296" Foreground="White"/>
</Grid>
</Grid>
That way of selection changed can be accomplished easily:
Have a look here:
<Window x:Class="ListBoxSelection.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">
<DockPanel>
<ListBox ItemsSource="{Binding persons}" IsSynchronizedWithCurrentItem="True" DockPanel.Dock="Top">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Margin="5,0"/>
<TextBlock Text="{Binding Age, StringFormat=is {0} years old}" Margin="5,0"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Orientation="Horizontal" DataContext="{Binding persons}" DockPanel.Dock="Top">
<TextBlock Text="You have selected: " FontWeight="SemiBold"/>
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"
Margin="5,0"
FontWeight="SemiBold"
VerticalAlignment="Top"
HorizontalAlignment="Center"/>
<TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}"
Margin="5,0"
FontWeight="SemiBold"
VerticalAlignment="Top"
HorizontalAlignment="Left"/>
</StackPanel>
<Button Content="Add Item" DockPanel.Dock="Top" Width="60" VerticalAlignment="Top" Margin="20" Click="btnAddItem_Click"/>
</DockPanel>
Note this down: IsSynchronizedWithCurrentItem="True"
From MSDN:
Gets or sets a value that indicates whether a Selector should keep the
SelectedItem synchronized with the current item in the Items property.
What's the next step? Display the selected item:
<StackPanel DataContext="{Binding persons}"/>
StackPanel is not an ItemsControl, it will not try to display all the items in persons but instead it will look for the selected one.
The ICollectionView interface contains a member called CurrentItem. What the IsSynchronizedWithCurrentItem does is: whenever an item is clicked on the ItemsControl, it sets the CurrentItem for the collection view. The ICollectionView also has two events: CurrentItemChanging and CurrentItemChanged. When the IsSynchronizedWithCurrentItem property is set, the ItemsControl will update the SelectedItem based on what the ICollectionView's CurrentItem is.
Further more, using UpdateSourceTrigger=PropertyChanged you will be able to update you selected item and this will be immediately displayed in the ListBox.
OK, that's about, here is the rest of the code:
public class Person : INotifyPropertyChanged
{
private string _Name;
public string Name
{
get { return _Name; }
set
{
_Name = value;
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
private int _Age;
public int Age
{
get { return _Age; }
set
{
_Age = value;
PropertyChanged(this, new PropertyChangedEventArgs("Age"));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
And the codebehind:
public partial class MainWindow : Window
{
public ObservableCollection<Person> persons { get; set; }
public Person SelectedPerson
{
get { return (Person)GetValue(SelectedPersonProperty); }
set { SetValue(SelectedPersonProperty, value); }
}
// Using a DependencyProperty as the backing store for SelectedPerson. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedPersonProperty =
DependencyProperty.Register("SelectedPerson", typeof(Person), typeof(MainWindow), new PropertyMetadata(null));
public MainWindow()
{
InitializeComponent();
persons = new ObservableCollection<Person>();
persons.Add(new Person() { Name = "Name1", Age = 20 });
persons.Add(new Person() { Name = "Name2", Age = 25 });
persons.Add(new Person() { Name = "Name3", Age = 30 });
this.DataContext = this;
}
private void btnAddItem_Click(object sender, RoutedEventArgs e)
{
persons.Add(new Person() { Name = "NameAdded", Age = 50 });
}
}
As you see, your SelectionChanged handler is not needed anymore.
You may be asking, what is that SelectedPerson in the code behind:
Add this binding on the ListBox:
SelectedItem="{Binding SelectedPerson}"
And in that AddToSprint_Click use the SelectedPerson to get the Person instead of directly accessing the ListBox.

How to bind or get properties from User Control

have a bit of a problem understanding some usercontrol interaction:
I've built this color picker. I have four sliders that change the color in Red, Green, & Blue (RGB and all that) as well as its opacity(alpha). When I slide these back and forth, I get a live response from the previewColor Rectangle(the fill color of the rectangle changes as I slide any of the sliders). All these elements are inside my user control.
In my main window, I have two signigicant elements, a blank canvas and a "change canvas" button. Ideally, when I play with the sliders in my user control and find a color i like, I would just click the ChangeCanvas button and the canvas background would change to match the current color of the previewRectangle.
The problem is that I cannot figure out how to bind the current color of the previewRectangle to a button action that my canvas will accept. Is there any way to bind the background of my canvas to the fill of my rectangle via button action? Or is it better to pass the color property from the usercontrol to the mainwindow?
Main Window XAML & Code
<Window x:Class="C_ShapeCanvasV2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:schafec="clr-namespace:C_ShapeCanvasV2.SControl"
Title="ColorCanvas" Height="393" Width="729">
<Grid Background="Gray">
<Canvas Name="MainCanvas" MouseLeftButtonDown="MainCanvas_MouseLeftButtonDown" ClipToBounds="True" MouseRightButtonDown="MainCanvas_MouseRightButtonDown" Background="White" HorizontalAlignment="Left" Height="363" VerticalAlignment="Top" Width="305"/>
<!-- user control -->
<schafec:ColorControls x:Name="colorControls" Margin="330,21,23,189"/>
<!-- user control -->
<Button Name="ChangeCanvas" Click="ChangeCanvas_Click" Content="Change Canvas" HorizontalAlignment="Left" Margin="456,209,0,0" VerticalAlignment="Top" Width="158" />
<Button Name="clearButton" Click="clearButton_Click" Content="Clear" HorizontalAlignment="Left" Margin="498,236,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
namespace C_ShapeCanvasV2
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
//---------------------------------------------------------------------------------------------//
private void ChangeCanvas_Click(object sender, RoutedEventArgs e)
{
//attempted -- not working
//MainCanvas.Background = new SolidColorBrush(clr);
}
private void clearButton_Click(object sender, RoutedEventArgs e)
{
MainCanvas.Children.Clear();
MainCanvas.Background = new SolidColorBrush(Colors.White);
}
}
}
UserControl XAML & Code
<UserControl x:Class="C_ShapeCanvasV2.SControl.ColorControls"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="153" Width="368">
<Grid Name="mainGrid" Background ="Gray" Margin="0,6,0,-6">
<!-- just an image under the previewRectangle to provide contrast for opacity purposes -->
<Rectangle Name="underImage" HorizontalAlignment="Left" Height="58" Margin="24,52,0,0" Stroke="Black" VerticalAlignment="Top" Width="64">
<Rectangle.Fill>
<ImageBrush ImageSource ="/C_ShapeCanvasV2;component/Images/ops.png"/>
</Rectangle.Fill>
</Rectangle>
<!-- PreviewColor Rectangle -->
<Rectangle Name="previewColor" HorizontalAlignment="Left" Height="58" Margin="24,52,0,0" Stroke="Black" VerticalAlignment="Top" Width="64"/>
<Slider Name="redSlider" Minimum="0" ValueChanged="redSlider_ValueChanged" IsSnapToTickEnabled="True" Maximum="255" TickFrequency="1" HorizontalAlignment="Left" Margin="211,36,0,0" VerticalAlignment="Top" Width="104"/>
<Slider Name="greenSlider" Minimum="0" ValueChanged="greenSlider_ValueChanged" IsSnapToTickEnabled="True" Maximum="255" TickFrequency="1" HorizontalAlignment="Left" Margin="211,61,0,0" VerticalAlignment="Top" Width="104" />
<Slider Name="blueSlider" Minimum="0" ValueChanged="blueSlider_ValueChanged" IsSnapToTickEnabled="True" Maximum="255" TickFrequency="1" HorizontalAlignment="Left" Margin="211,86,0,0" VerticalAlignment="Top" Width="104"/>
<Slider Name="alphaSlider" Minimum="0" ValueChanged="alphaSlider_ValueChanged" IsSnapToTickEnabled="True" Maximum="255" TickFrequency="1" HorizontalAlignment="Left" Margin="211,111,0,0" VerticalAlignment="Top" Width="104"/>
<Label Content="Red" HorizontalAlignment="Left" Margin="112,34,0,0" VerticalAlignment="Top"/>
<Label Content="Green" HorizontalAlignment="Left" Margin="112,57,0,0" VerticalAlignment="Top"/>
<Label Content="Blue" HorizontalAlignment="Left" Margin="112,82,0,0" VerticalAlignment="Top"/>
<Label Content="Alpha" HorizontalAlignment="Left" Margin="112,107,0,0" VerticalAlignment="Top"/>
<Label Name="redLabel" Content="{Binding ElementName= redSlider, Path=Value}" HorizontalAlignment="Left" Margin="318,32,0,0" VerticalAlignment="Top"/>
<Label Name="greenLabel" Content="{Binding ElementName= greenSlider, Path=Value}" HorizontalAlignment="Left" Margin="318,59,0,0" VerticalAlignment="Top"/>
<Label Name="blueLabel" Content="{Binding ElementName= blueSlider, Path=Value}" HorizontalAlignment="Left" Margin="318,82,0,0" VerticalAlignment="Top"/>
<Label Name="alphaLabel" Content="{Binding ElementName= alphaSlider, Path=Value}" HorizontalAlignment="Left" Margin="318,107,0,0" VerticalAlignment="Top"/>
</Grid>
namespace C_ShapeCanvasV2.SControl
{
public partial class ColorControls : UserControl
{
public Color clr;
public ColorControls()
{
InitializeComponent();
}
private void changeColorSystem()
{
clr = Color.FromArgb(Convert.ToByte(alphaSlider.Value), Convert.ToByte(redSlider.Value), Convert.ToByte(greenSlider.Value), Convert.ToByte(blueSlider.Value));
previewColor.Fill = new SolidColorBrush(clr);
}
//public void setColor(Color g)
//{
// Color c = g;
//}
//public Color getColor()
//{
// return clr;
//}
private void alphaSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
changeColorSystem();
}
private void blueSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
changeColorSystem();
}
private void greenSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
changeColorSystem();
}
private void redSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
changeColorSystem();
}
}
}
That would not be clean in my opinion, but this piece of code should work:
private void ChangeCanvas_Click(object sender, RoutedEventArgs e)
{
MainCanvas.Background = colorControls.previewColor.Fill;
}
Still you should really inform yourself about MVVM architecture to do it in a more clean/testable way.
Hope it helps.

Is there a Silverlight equivalent to "Application.OpenForms"?

Basically, I'm trying to take information entered by the user on one page and print it out to another page via a "printer friendly" version, or report, of something. I have a MainPage.xaml that is, as the name suggests, my main page, but in a window there is the subpage AdCalculator.xaml where the user enters the information and PrintEstimate.xaml that is navigated to via a button on AdCalculator.
I would like to be able to transfer the information entered in the textboxes from AdCalculator and print it out via text blocks in PrintEstimate. So in order to do that I have the following code:
Views.AdCalculator AdCalc = new Views.AdCalculator();
string PrintCompanyName = AdCalc.CompanyName;
string PrintContactName = AdCalc.txt_CustomerName.Text;
string PrintBillingAddress1 = AdCalc.txt_BillingAddress.Text;
string PrintBillingAddress2 = AdCalc.txt_BillingAddressLine2.Text;
string PrintPhoneNumber = AdCalc.txt_PhoneNumber.Text;
string PrintNumOfAds = AdCalc.txt_NumofAds.Text;
string PrintRateOfPlay = AdCalc.Cmb_Rate.SelectedValue.ToString();
string PrintNumOfMonths = AdCalc.txt_NumofMonths.Text;
string PrintTotalDue = AdCalc.txt_InvoiceSummary_TotalDue.Text;
PrintEstimate PrintEstimatePage = new PrintEstimate();
PrintEstimatePage.txt_CompanyName.Text = PrintCompanyName;
PrintEstimatePage.txt_CustomerName.Text = PrintContactName;
PrintEstimatePage.txt_BillingAddress.Text = PrintBillingAddress1;
PrintEstimatePage.txt_BillingAddressLine2.Text = PrintBillingAddress2;
PrintEstimatePage.txt_PhoneNumber.Text = PrintPhoneNumber;
PrintEstimatePage.txt_InvoiceSummary_NumofAds.Text = PrintNumOfAds;
PrintEstimatePage.txt_InvoiceSummary_RateofPlay.Text = PrintRateOfPlay;
PrintEstimatePage.txt_InvoiceSummary_NumOfMonths.Text = PrintNumOfMonths;
PrintEstimatePage.txt_EstimateTotal.Text = PrintTotalDue;
Only problem is, when I instantiate the new AdCalculator page, it clears the values, so nothing is actually retained as far as user-input goes. Following a lead from a colleague, I believe all I need to do is change the line
Views.AdCalculator AdCalc = new Views.AdCalculator();
to
Views.AdCalculator AdCalc = (AdCalculator)Application.OpenForms["AdCalculator"];
except the "Apllication.OpenForms" doesn't register. I know there are a lot of differences in the way C# code-behind is laid out for silverlight applications, so I didn't know if there was an equivalent that anyone knew about to "Application.OpenForms" that would help solve my issue or if there was any other way to go about getting my task done.
If I understand your question correctly you simply want to get some user input and display it.
I suggest you start by defining a class that will represent the data you are inputting,
for example:
public class Customer
{
public string ContectName { get; set; }
public string BillingAddress1 { get; set; }
public string BillingAddress2 { get; set; }
public string PhoneNumber { get; set; }
public int NumOfAds { get; set; }
public double RateOfPlay { get; set; }
public int NumOfMonths { get; set; }
public double TotalDue { get; set; }
}
On the page where the user inputs data you then create an instance
of this class, either by manually creating an instance and setting
its properties when the user submits (similar to what you are doing in your code)
or use databinding to your advantage (which is what I prefer).
Let's say for example you are inputting data on your MainPage
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
this.DataContext = new Customer();
}
Now you can bind the controls. Let's say you're using a grid:
<Grid x:Name="LayoutRoot" Background="White">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<sdk:Label Content="Billing Address 1:" Grid.Column="0" Grid.Row="0" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="0" Height="23" HorizontalAlignment="Left" Margin="3" Name="billingAddress1TextBox" Text="{Binding Path=BillingAddress1, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Billing Address 2:" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="3" Name="billingAddress2TextBox" Text="{Binding Path=BillingAddress2, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Contect Name:" Grid.Column="0" Grid.Row="2" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="3" Name="contectNameTextBox" Text="{Binding Path=ContectName, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Num Of Ads:" Grid.Column="0" Grid.Row="3" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="3" Height="23" HorizontalAlignment="Left" Margin="3" Name="numOfAdsTextBox" Text="{Binding Path=NumOfAds, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Num Of Months:" Grid.Column="0" Grid.Row="4" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="4" Height="23" HorizontalAlignment="Left" Margin="3" Name="numOfMonthsTextBox" Text="{Binding Path=NumOfMonths, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Phone Number:" Grid.Column="0" Grid.Row="5" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="5" Height="23" HorizontalAlignment="Left" Margin="3" Name="phoneNumberTextBox" Text="{Binding Path=PhoneNumber, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Rate Of Play:" Grid.Column="0" Grid.Row="6" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="6" Height="23" HorizontalAlignment="Left" Margin="3" Name="rateOfPlayTextBox" Text="{Binding Path=RateOfPlay, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Total Due:" Grid.Column="0" Grid.Row="7" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="7" Height="23" HorizontalAlignment="Left" Margin="3" Name="totalDueTextBox" Text="{Binding Path=TotalDue, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
</Grid>
</Grid>
When the user clicks the submit button, you can use something like this:
private void Button_Click(object sender, RoutedEventArgs e)
{
var currentCustomer = this.DataContext as Customer;
var previewWindow = new PrintPreviewWindow(currentCustomer);
previewWindow.Show();
}
For this to work you'll need to have a Silverlight ChildWindow like this:
public partial class PrintPreviewWindow : ChildWindow
{
public PrintPreviewWindow(Customer customer)
{
InitializeComponent();
this.DataContext = customer;
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
}
}
So your MainPage creates a new instance of the PrintPreviewChildWindow (could be a page as well if you prefer) and passes along the customer instance. The ChildWindow can then do whatever it wants with it. When the ChildWindow closes, you'll probably want to empty the input page, you can do this by simply setting the data context again:
this.DataContext = new Customer();
I'm guessing this is what you are looking for.
Try to get into the whole data binding stuff, it will save you lots and lots of lines of code. And let us know if this answers your question or if you have more :-)

Categories