How to bind or get properties from User Control - c#

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.

Related

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;

passing values between two pages wpf

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/

Accessing items in DataTemplate using Visual Tree Helper in ListBox

I have the following DataTemplate:
<DataTemplate x:Key="ToDoListBoxItemTemplate">
<Grid x:Name="item2Expanded" HorizontalAlignment="Left" VerticalAlignment="Top" Width="480" Background="{Binding Converter={StaticResource RowColour}}" MinHeight="81">
<StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Width="420" Margin="60,0,0,0">
<TextBox x:Name="taskTitle" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding ItemName}" VerticalAlignment="Top" Width="420" Background="{x:Null}" BorderBrush="{x:Null}" CaretBrush="#FF0080FF" SelectionBackground="#FFCFCFCF" Foreground="#FF4E4E4E" BorderThickness="3,3,3,6" FontSize="29.333" Style="{StaticResource listTextBoxTemplate}" InputScope="Text" SelectionForeground="#FF4E4E4E" KeyUp="taskTitle_KeyUp" LostFocus="taskTitle_LostFocus" Tap="taskTitle_Tap" IsReadOnly="True" Margin="0,1,0,0" DoubleTap="taskTitle_DoubleTap"/>
<TextBox x:Name="taskDetail" HorizontalAlignment="Left" TextWrapping="Wrap" Text="Tea is an essential English beverage, it has a nice calming effect, and is often served alongside biscuits." VerticalAlignment="Top" Width="420" Background="{x:Null}" BorderBrush="{x:Null}" CaretBrush="#FF0080FF" SelectionBackground="#FFCFCFCF" Foreground="#FF878787" BorderThickness="3,0,3,6" FontSize="21.333" Style="{StaticResource listTextBoxTemplate}" InputScope="Text" SelectionForeground="#FF878787" Margin="0,-20,0,0" KeyUp="taskDetail_KeyUp" LostFocus="taskDetail_LostFocus" Padding="2,5,2,2" IsHitTestVisible="False"/>
<Grid Height="170" Margin="0,-20,0,0">
<Button x:Name="chooseDateButton" Content="27/06/2013" HorizontalAlignment="Left" Margin="6,13,0,0" VerticalAlignment="Top" BorderBrush="#FF959595" Foreground="#FF959595" Width="157" HorizontalContentAlignment="Left" FontSize="20" Style="{StaticResource selectorButtonTemplate}"/>
<Button x:Name="chooseTimeButton" Content="12:00" HorizontalAlignment="Left" Margin="146,13,0,0" VerticalAlignment="Top" BorderBrush="#FF959595" Foreground="#FF959595" Width="99" HorizontalContentAlignment="Left" FontSize="20" Style="{StaticResource selectorButtonTemplate}"/>
<Button x:Name="setOrClearButton" Content="REMIND ME" HorizontalAlignment="Left" Margin="228,13,0,0" VerticalAlignment="Top" BorderBrush="#FF959595" Foreground="White" Width="180" FontSize="20" Background="#FF959595" Style="{StaticResource greyButtonTemplate}"/>
<Button x:Name="deleteButton" Content="DELETE TASK" HorizontalAlignment="Left" Margin="6,85,0,0" VerticalAlignment="Top" BorderBrush="#FFEE4747" Foreground="White" Width="180" FontSize="20" Background="#FFEE4747" Style="{StaticResource redButtonTemplate}"/>
<Image x:Name="retractButton" Margin="347,107,21,11" Source="/Assets/retract.png" Stretch="Fill" Tap="retractButton_Tap"/>
</Grid>
</StackPanel>
<CheckBox x:Name="checkBox" IsChecked="{Binding IsComplete, Mode=TwoWay}" Content="" HorizontalAlignment="Left" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="{x:Null}" Width="72" BorderThickness="0" Template="{StaticResource checkBoxTemplate}" Checked="checkBox_Checked" Unchecked="checkBox_Unchecked"/>
</Grid>
</DataTemplate>
Where the Grid item2Expanded is placed dynamically in a ListBox (Name="allToDoItemsListBox"). Text is added to each item via bindings.
The image retractButton has Tap="retractButton_Tap", As shown in the code:
private void retractButton_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
if (isItemExpanded == true)
{
// Compacts current item
itemGrid.Height = taskTitle.ActualHeight; // Restores itemGrid height to fit only taskTitle
taskTitle.IsReadOnly = true; // taskTitle becomes only double-tap editable, single tap to expand once more
taskDetail.IsHitTestVisible = false; // Stops overlapping taps
isItemExpanded = false;
}
// Adds the event handler for single tap event
tapTimer.Tick += new EventHandler(tapTimer_Tick);
tapTimer.Start();
}
private void tapTimer_Tick(object sender, EventArgs e)
{
// Stop timer
tapTimer.Tick -= new EventHandler(tapTimer_Tick);
tapTimer.Stop();
// Rest of the single tap function
if (isItemExpanded == false)
{
taskDetail.IsHitTestVisible = true;
taskDetail.IsEnabled = false;
// Expands current item
itemGrid.Height = double.NaN; // Sets itemGrid height to auto
isItemExpanded = true;
// Yeah... don't ask.
// Stops temporary text highlighting/auto jumping to keyboard
taskTitle.IsEnabled = false;
taskTitle.IsEnabled = true;
taskDetail.IsEnabled = true;
}
}
But I cannot access itemGrid, taskTitle, or taskDetail for this specific item. And I have no idea how to pass them to the tapTimer_Tick function.
I have been able to use the Tag="{binding itemID}" on elements, but that still hasn't allowed me to solve this issue.
How do I find the grid item2Expanded that the Tap originated from, and then access elements in the same grid by name?
If I want to access the same element as was clicked, then it's easy:
private void taskTitle_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
TextBox taskTitle = (TextBox)sender;
taskTitle.IsEnabled = false;
}
I've been trying to work out how to use Visual Tree Helper to solve this problem, but I have no idea how to do it.

Issue to Change button value dynamically in wpf

<Grid x:Name="LayoutRoot">
<Button x:Name="btn_num" Width="51" Margin="318.849,158,262.15,0" Height="45" VerticalAlignment="Top" d:LayoutOverrides="HorizontalMargin">
<Grid Height="38.166" Width="44.833">
<Label x:Name="lbl_2" Content="2" Margin="4.483,-2.042,7,-1.626" FontSize="11.333"/>
<Label x:Name="lbl_1" Content="1" Margin="4.483,0,7,-19.251" FontSize="11.333" Height="41.834" VerticalAlignment="Bottom"/>
<Label x:Name="lbl_3" Content="3" Margin="0,8.083,-15,-11.751" FontSize="11.333" HorizontalAlignment="Right" Width="33.35" Foreground="Black"/>
</Grid>
</Button>
<Button x:Name="btn_a" Content="A" HorizontalAlignment="Left" Margin="225.333,158,0,0" Width="55" Foreground="Black" Height="45" VerticalAlignment="Top" Click="btn_alt_Click" />
</Grid>
It's design will be like this
public partial class button : Window
{
static int _AClick = 0;
public button()
{
this.InitializeComponent();
}
private void btn_alt_Click(object sender, RoutedEventArgs e)
{
if (_AClick == 0)
{
_AClick = 1;
Fill();
}
else
{
btn_num.Content = "";
_AClick = 0;
}
}
public void Fill()
{
btn_num.Content = "3";
}
}
The result after window loaded
If i click A button first time. The result will be like this
If I click A button second time. The result will be like this
when I click A button second time. I need the result like below. what should I do for that.
There are a lot of ways available in WPF to achieve this. One way to do this is to have two ControlTemplates (one having all three numbers and other having just one number) and then set the template of your button in code -
<Grid x:Name="LayoutRoot">
<Grid.Resources>
<ControlTemplate
x:Key="threeNumberTemplate"
TargetType="{x:Type Button}">
<Grid Height="38.166" Width="44.833">
<Label x:Name="lbl_2" Content="2" Margin="4.483,-2.042,7,-1.626" FontSize="11.333"/>
<Label x:Name="lbl_1" Content="1" Margin="4.483,0,7,-19.251" FontSize="11.333" Height="41.834" VerticalAlignment="Bottom"/>
<Label x:Name="lbl_3" Content="3" Margin="0,8.083,-15,-11.751" FontSize="11.333" HorizontalAlignment="Right" Width="33.35" Foreground="Black"/>
</Grid>
</ControlTemplate>
<ControlTemplate
x:Key="oneNumberTemplate"
TargetType="{x:Type Button}">
<Label x:Name="lbl_3" Content="3" FontSize="11.333"/>
</ControlTemplate>
</Grid.Resources>
<Button x:Name="btn_num" Width="51" Margin="318.849,158,262.15,0" Height="45" VerticalAlignment="Top" Template="{StaticResource threeNumberTemplate}"></Button>
<Button x:Name="btn_a" Content="A" HorizontalAlignment="Left" Margin="225.333,158,0,0" Width="55" Foreground="Black" Height="45" VerticalAlignment="Top" Click="btn_alt_Click" />
</Grid>
Code behind -
private void btn_alt_Click(object sender, RoutedEventArgs e)
{
if (_AClick == 0)
{
_AClick = 1;
btn_num.Template = FindResource("oneNumberTemplate") as ControlTemplate;
}
else
{
btn_num.Template = FindResource("threeNumberTemplate") as ControlTemplate;
_AClick = 0;
}
}
Same can be achieved through triggers by making _AClick as DependecyProperty and using it's value to swap templates in triggers.
Another approach is to have two Buttons and hide/show them based on the _AClick value in code.
You can create three DataTemplate and use DataTemplateSelector class to load the corresponding data template on run time.
MSDN - DataTemplateSelector

adding row dyanamicaly to gridview in WPF

Please help me with the following code,I want to add a row inputted by user to a gridview.
I am able to add a row but its empty!!Please help.it worked in windows forms but its not working with WPF.
private void button1_Click(object sender, RoutedEventArgs e)
{
GetGridView();
}
private void GetGridView()
{
string[] row0 = {textBox1.Text,"Beatles" };
dataGrid1.Items.Add(row0);
dataGrid1.Columns[0].DisplayIndex = 0;
dataGrid1.Columns[1].DisplayIndex = 1;
}
//////////////
sure,here it is
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="964">
<Grid>
<DataGrid AutoGenerateColumns="False" Height="274" HorizontalAlignment="Left" Margin="509,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="239" DataContext="{Binding}" ItemsSource="{Binding}" ItemStringFormat="{Binding}" SelectedIndex="-1" SelectionChanged="dataGrid1_SelectionChanged">
<DataGrid.Columns>
<DataGridTextColumn Header="Header1" />
<DataGridTextColumn Header="Header" />
</DataGrid.Columns>
</DataGrid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="184,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" TextChanged="textBox1_TextChanged" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="184,187,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="184,125,0,0" Name="textBox3" VerticalAlignment="Top" Width="120" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="184,66,0,0" Name="textBox4" VerticalAlignment="Top" Width="120" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="414,231,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
Edit: You bound the ItemsSource of the DataGrid, you cannot add items to the grid itself while that is the case, add the items to the bound collection (which is what i originally suggested)
I would not suggest you do anything like that. In WPF you should bind your controls to the data, that way you can change the source-collection and the grid will get updated automatically, which is less messy than using any method like DataGrid.Items.Add which accepts input of type object.
e.g.
Xaml:
<DataGrid ItemsSource="{Binding GridData}" Name="DGrid"/>
<TextBox Name="TB" Width="100"/>
<Button Content="Add" Click="Button_Click"/>
Code:
private ObservableCollection<Employee> gridData = new ObservableCollection<Employee>();
public ObservableCollection<Employee> GridData
{
get { return gridData; }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
GridData.Add(new Employee(TB.Text, "Beatles?"));
}

Categories