C# & XAML how to get button to respond on first click - c#

I actually got the bulk of my code to work. I appreciate the input, it pointed me in the correct direction. The problem I am having now is getting the buttons to work on the first click.
I appreciate any input that would help me improve my code.
Below are my XAML (MainPage.xaml) & C# (MainPage.xaml.cs) code.
<Page
x:Class="Calculator_Application.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Calculator_Application"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<TextBlock x:Name="textBlock_title" TextWrapping="Wrap" Text="Calculator Application" VerticalAlignment="Top" Height="58" Width="252" Margin="86,30,0,0" SelectionChanged="textBlock_SelectionChanged" HorizontalAlignment="Left" FontSize="24" RenderTransformOrigin="-0.039,0.549" FontFamily="Calibri" Foreground="#FFBCB7B6"/>
<Button x:Name="button_info" Content="Information" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="135,561,0,0" Click="button_Click" FontFamily="Global User Interface" Foreground="#FFF05D5D"/>
<TextBox x:Name="textBox_number1" HorizontalAlignment="Left" Margin="29,191,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" TextChanged="textBox_number1_TextChanged"/>
<TextBox x:Name="textBox_number2" HorizontalAlignment="Left" Margin="29,387,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top"/>
<TextBlock x:Name="textBlock_info" HorizontalAlignment="Left" TextWrapping="Wrap" Text="Please input numbers to calculate:" VerticalAlignment="Top" Height="30" Width="252" FontSize="16" FontStyle="Italic" Margin="29,134,0,0" SelectionChanged="textBlock_info_SelectionChanged" Foreground="#FFE5957F"/>
<Button x:Name="button_add" Content="+" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="29,278,0,0" MinWidth="25" Height="20" FontSize="24" FontFamily="Global User Interface" Width="39" Background="Black"/>
<Button x:Name="button_subtract" Content="-" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="106,278,0,0" MinWidth="25" Height="20" FontSize="24" FontFamily="Global User Interface" Width="39"/>
<Button x:Name="button_multiply" Content="*" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="179,278,0,0" MinWidth="25" Height="20" FontSize="24" FontFamily="Global User Interface" Width="39"/>
<Button x:Name="button_divide" Content="/" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="257,278,0,0" MinWidth="25" Height="20" FontSize="24" FontFamily="Global User Interface" Width="39"/>
<TextBlock x:Name="textBlock_equals" HorizontalAlignment="Left" TextWrapping="Wrap" Text="=" VerticalAlignment="Top" Height="39" Width="38" Margin="164,387,0,0" FontSize="36"/>
<TextBlock x:Name="textBlock_answer" HorizontalAlignment="Left" TextWrapping="Wrap" Text="answer" VerticalAlignment="Center" Height="23" Width="139" Margin="207,387,0,230" FontSize="22"/>
</Grid>
</Page>
Here is the C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// Added to ensure popup is availible
using Windows.UI.Popups;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641
namespace Calculator_Application
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private double valHolder1 = 0;
private double valHolder2 = 0;
private double answer = 0;
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
private void textBlock_SelectionChanged(object sender, RoutedEventArgs e)
{
}
private void textBlock_info_SelectionChanged(object sender, RoutedEventArgs e)
{
}
private async void button_Click(object sender, RoutedEventArgs e)
{
//Creating instance for the MessageDialog Class
//and passing the message in it's Constructor
MessageDialog msgbox = new MessageDialog("Page Lynn Potter, MBL 410, 05-15-2017, Robin Deitsch");
//Calling the Show method of MessageDialog class
//which will show the MessageBox
await msgbox.ShowAsync();
}
private void textBox_number1_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void button_add_Click(object sender, RoutedEventArgs e)
{
//Make sure out text box has a value
if (textBox_number1.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder1 = System.Double.Parse(textBox_number1.Text);
//Empty the text box
textBox_number1.Text = string.Empty;
if (textBox_number2.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder2 = System.Double.Parse(textBox_number2.Text);
//Empty the text box
textBox_number2.Text = string.Empty;
}
}
else
{
//Calculate answer
answer = valHolder1 + valHolder2;
//Assign answer to text block
textBlock_answer.Text = answer.ToString();
}
}
private void button_subtract_Click(object sender, RoutedEventArgs e)
{
//Make sure out text box has a value
if (textBox_number1.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder1 = System.Double.Parse(textBox_number1.Text);
//Empty the text box
textBox_number1.Text = string.Empty;
if (textBox_number2.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder2 = System.Double.Parse(textBox_number2.Text);
//Empty the text box
textBox_number2.Text = string.Empty;
}
}
else
{
//Calculate answer
answer = valHolder1 - valHolder2;
//Assign answer to text block
textBlock_answer.Text = answer.ToString();
}
}
private void button_multiply_Click(object sender, RoutedEventArgs e)
{
//Make sure out text box has a value
if (textBox_number1.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder1 = System.Double.Parse(textBox_number1.Text);
//Empty the text box
textBox_number1.Text = string.Empty;
if (textBox_number2.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder2 = System.Double.Parse(textBox_number2.Text);
//Empty the text box
textBox_number2.Text = string.Empty;
}
}
else
{
//Calculate answer
answer = valHolder1 * valHolder2;
//Assign answer to text block
textBlock_answer.Text = answer.ToString();
}
}
private void button_divide_Click(object sender, RoutedEventArgs e)
{
//Make sure out text box has a value
if (textBox_number1.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder1 = System.Double.Parse(textBox_number1.Text);
//Empty the text box
textBox_number1.Text = string.Empty;
if (textBox_number2.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder2 = System.Double.Parse(textBox_number2.Text);
//Empty the text box
textBox_number2.Text = string.Empty;
}
}
else
{
//Calculate answer
answer = valHolder1 / valHolder2;
//Assign answer to text block
textBlock_answer.Text = answer.ToString();
}
}
}
}

You have an event handler configured for the button_info button.
<Button x:Name="button_info" Content="Information"
HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="135,561,0,0"
FontFamily="Global User Interface" Foreground="#FFF05D5D"
Click="button_Click"/>
I don't see where you've configured handlers for the other buttons.
There should be something like this in the XAML.
<Button x:Name="button_add" Click = "button_add_Click" />
<Button x:Name="button_subtract" Click = "button_subtract_Click" />
<Button x:Name="button_multiply" Click = "button_multiply_Click" />
<Button x:Name="button_divide"Click = "button_divide_Click" />

Related

How to update textblock with method

I have a textbox that provide user to input string. how can i pass that string to method and toUpper() it. and pass back the string to textblock in the main window that both of the box and block update in real time?
For my C# code:
public MainWindow()
{
InitializeComponent();
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
textBlock.Text = textBox.Text +"changed";
}
it is just as simple like this.
for my xaml code:
<Grid >
<TextBox x:Name ="textBox" HorizontalAlignment="Left" Height="105" Margin="28,185,0,0" TextWrapping="Wrap" Text="HELLO" VerticalAlignment="Top" Width="300" TextChanged="TextBox_TextChanged"/>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Height="116" Margin="114,40,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="328"/>
</Grid>
i want to know why the text of my textblock cannot be updated when i type something inside the textbox.
I combined the answer of #Yavor Georgiev
You are encountering a null reference exception. When the textBox control is created it will trigger the textChange event on textBox and by that point, textBlock isn't created and is therefore null. You can just change the order of the textboxes in the XAML and you will be fine.
Change the order
Grid>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Height="116" Margin="114,40,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="328"/>
<TextBox x:Name ="textBox" HorizontalAlignment="Left" Height="105" Margin="28,185,0,0" TextWrapping="Wrap" Text="HELLO" VerticalAlignment="Top" Width="300" TextChanged="TextBox_TextChanged"/>
</Grid>
For the upper part i used #Yavor Georgiev answer when typing
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
textBox.Text = textBox.Text?.ToUpper();
textBlock.Text = textBox.Text;
textBox.CaretIndex = textBox.Text?.Length ?? 0;
textBlock.Text = textBox.Text + "changed";
}
Do you need something like this?
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
textBox.Text = textBox.Text?.ToUpper();
textBlock.Text = textBox.Text;
textBox.CaretIndex = textBox.Text?.Length ?? 0; //You need this to continue typing from the last index onwards..
}
I don't exactly understand if you need both the textBox and the textBlock to change at the same time or only the textBlock to be in UpperCase, but the concept is the same

Second WPF window is blank

The second window in my WPF window is blank.
I've tried declaring the variable in multiple places, and assigning the value of new Send() separately from the declaration.
I've also made sure it isn't just my computer. I sent the compiled program to someone else and it did the same thing.
private void Button_Click(object sender, RoutedEventArgs e)
{
Send send = new Send();
send.Show();
}
The Send class:
public partial class Send : Window
{
public Send()
{
InitializeComponent();
ipIdBox.Text = GenerateIPID(GetIPAddress(), 8000);
}
private string GetIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
private string GenerateIPID(string ip, int port)
{
string[] ipseps = ip.Split('.'); // Split IP into parts
string code = ""; // Initialize the code
int counter = 0; // A counter (because every 4 digits are seperated)
foreach (string ippart in ipseps)
{
int ipparti = Convert.ToInt32(ippart);
string hippart = ipparti.ToString("X2");
code += hippart;
counter++;
if (counter == 1) {
counter = 0;
code += "-";
}
}
code += $"-{port.ToString("X4")}";
return code;
}
}
... and it's XAML
<Window x:Class="ScistMain.Send"
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:ScistMain"
mc:Ignorable="d"
Title="Send" Height="264.95" Width="451.774" OverridesDefaultStyle="True" Topmost="True">
<Grid>
<TextBlock x:Name="ipIdBox" Margin="0,124,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="34" TextAlignment="Center" FontSize="24" Text="7F00-0001-8000"/>
<TextBlock Margin="0,108,0,0" TextWrapping="Wrap" Text="Tell the person recieving to type this code:" VerticalAlignment="Top" Width="444" TextAlignment="Center"/>
<TextBlock Margin="0,10,0,0" TextWrapping="Wrap" Text="You are sending:" VerticalAlignment="Top" TextAlignment="Center" FontSize="18" FontWeight="Bold"/>
<Image x:Name="iconImg" Height="32" Margin="206,39,206,0" VerticalAlignment="Top" Width="32" Source="Resources/scist.ico"/>
<TextBlock Margin="0,76,0,0" TextWrapping="Wrap" Text="Placeholder Program" VerticalAlignment="Top" TextAlignment="Center"/>
<ProgressBar x:Name="pBar" HorizontalAlignment="Left" Height="34" Margin="10,124,0,0" VerticalAlignment="Top" Width="424" Visibility="Collapsed"/>
<Button Content="Cancel" HorizontalAlignment="Left" Margin="359,203,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</Window>
I expect it to show the window I created in the designer:
but instead it shows a black window.
OverridesDefaultStyle="True" on the Window tag was the issue.

How can I change the content of a xaml page when a user clicks on a radio button? C# UWP

Hello Stack Overflow community,
I am developing a weather application using the Universal Windows Platform.
I am also using openweathermap to collect my weather data and Json.Net to parse the Json data that the api returns.
I have designed my app with a navigation pane using a split view control and a frame.
Inside of the frame I have placed a relative panel. In the xaml code I have provided you can see the content I would like to place inside of the frame when the user clicks on the radio button.
What I need to do is fill out the function named CurrentWeather_Checked, it's currently empty, but I am not sure what I need to put in there to get the behavior that I want.
1.MainPage.xaml
<Page
x:Class="Susanoo.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Susanoo"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ThemesGeneric.xaml"/>
<ResourceDictionary Source="ThemesText.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Page.Resources>
<SplitView x:Name="NavigationPane" DisplayMode="CompactInline">
<SplitView.Pane>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="44" />
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button x:Name="HamburgerButton" Grid.Row="0" Style="{StaticResource MenuItemButtonStyle}" Tag="" Click="HamburgerButton_Click" />
<StackPanel x:Name="NavigationMenu" Orientation="Vertical" Grid.Row="1" Background="#FF42424C">
<RadioButton x:Name="Option1"
GroupName="Group1"
Style="{StaticResource NavigationButtonStyle}"
Tag=""
Checked="CurrentWeather_Checked"
Content="Current Weather"
/>
<RadioButton x:Name="Option2"
GroupName="Group1"
Style="{StaticResource NavigationButtonStyle}"
Tag=""
Checked="Option2Button_Checked"
Content="Favorite Cities"
/>
</StackPanel>
</Grid>
</SplitView.Pane>
<SplitView.Content>
<Frame x:Name="Content" Background="#FF31A877">
<Frame.ContentTransitions>
<TransitionCollection>
<NavigationThemeTransition>
<NavigationThemeTransition.DefaultNavigationTransitionInfo>
<EntranceNavigationTransitionInfo/>
</NavigationThemeTransition.DefaultNavigationTransitionInfo>
</NavigationThemeTransition>
</TransitionCollection>
</Frame.ContentTransitions>
<RelativePanel x:Name="contentDisplay">
<TextBlock x:Name="cityName" Style="{StaticResource displayText}" RelativePanel.AlignHorizontalCenterWithPanel="True" Text="City"/>
<TextBlock x:Name="countryName" Style="{StaticResource displayText}" RelativePanel.AlignHorizontalCenterWithPanel="True" RelativePanel.Below="cityName" Text="Country"/>
<TextBlock x:Name="currentTemp" Style="{StaticResource displayText}" RelativePanel.AlignHorizontalCenterWithPanel="True" RelativePanel.AlignVerticalCenterWithPanel="True" Text="Temp"/>
<TextBlock x:Name="minTemp" Style="{StaticResource smallDisplayText}" RelativePanel.LeftOf="countryName" RelativePanel.Below="currentTemp" Text="Min"/>
<TextBlock x:Name="maxTemp" Style="{StaticResource smallDisplayText}" RelativePanel.RightOf="countryName" RelativePanel.Below="currentTemp" Text="Max"/>
</RelativePanel>
</Frame>
</SplitView.Content>
</SplitView>
</Page>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace Susanoo
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize;
// Set the min size to 550 * 600
ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size { Width = 550, Height = 600 });
getCurrentWeather();
TitleBar();
}
async void getCurrentWeather()
{
WeatherObject currentWeather = new WeatherObject();
//units in Fahrenheit by default
currentWeather.Units = "Imperial";
//Searcy default for testing
currentWeather.RootObject.Name = "Searcy";
currentWeather.ZipCode = "72149";
await currentWeather.Task_getWeatherInfoByCityName();
//await currentWeather.Task_getWeatherInfoByZipCode();
if (currentWeather.RootObject != null)
{
cityName.Text = currentWeather.RootObject.Name;
countryName.Text = currentWeather.RootObject.Sys.Country;
currentTemp.Text = currentWeather.RootObject.Main.Temp.ToString();
if (currentWeather.Units == "Imperial")
{
currentTemp.Text = Math.Floor(currentWeather.RootObject.Main.Temp).ToString() + "° F";
minTemp.Text = "Low: " + Math.Floor(currentWeather.RootObject.Main.Temp_Min).ToString() + "°";
maxTemp.Text = "High: " + Math.Floor(currentWeather.RootObject.Main.Temp_Max).ToString() + "°";
}
else if (currentWeather.Units == "Metric")
{
currentTemp.Text = Math.Floor(currentWeather.RootObject.Main.Temp).ToString() + "° C";
minTemp.Text = "Low: " + Math.Floor(currentWeather.RootObject.Main.Temp_Min).ToString() + "°";
maxTemp.Text = "High: " + Math.Floor(currentWeather.RootObject.Main.Temp_Max).ToString() + "°";
}
//to use the images from openweathermap API
//not sure how to actually get it to show in the image in the main page?
string iconName = currentWeather.RootObject.Weather[0].Icon;
string imgUrl = "http://openweathermap.org/img/w/" + iconName + ".png";
//image.Source = imgUrl;
}
}
protected override void OnNavigatedTo(NavigationEventArgs args)
{
// Page was navigated to
var navManager = SystemNavigationManager.GetForCurrentView();
if (this.Frame.CanGoBack)
{
// Show Back button in title bar
navManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
}
else
{
// Remove Back button from title bar
navManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
}
}
protected override void OnNavigatedFrom(NavigationEventArgs args)
{
// Page is being navigated away from
}
private void aboutButton_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(AboutPage));
}
private void TitleBar()
{
ApplicationViewTitleBar titleBar = ApplicationView.GetForCurrentView().TitleBar;
titleBar.BackgroundColor = Colors.Black;
titleBar.ForegroundColor = Colors.White;
titleBar.ButtonBackgroundColor = Colors.Black;
titleBar.ButtonForegroundColor = Colors.White;
}
public Frame AppFrame { get { return Content; } }
private void CurrentWeather_Checked(object sender, RoutedEventArgs e)
{
// Here is where I am expecting I need to put the code
}
private void Option2Button_Checked(object sender, RoutedEventArgs e)
{
}
private void HamburgerButton_Click(object sender, RoutedEventArgs e)
{
NavigationPane.IsPaneOpen = !NavigationPane.IsPaneOpen;
}
}
}

XamlParseException when loading page

I've found a weird problem in my app. When I open one of the pages, the app's InitializeComponent() method throws an XamlParseException. What can I do to get rid of this issue? I haven't found any obvious errors in my xaml code either. Here you can see my .cs and .xaml file of the page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
namespace app_name
{
public partial class newsummaryPage : PhoneApplicationPage
{
List<String> savingList;
List<String> projectList;
List<String> subjectsList;
IsolatedStorageSettings settings;
Boolean amISelectingProjects = true;
Boolean firstSelection = true;
String practicesummaryText;
public newsummaryPage()
{
InitializeComponent();
//Initialize settings
settings = IsolatedStorageSettings.ApplicationSettings;
}
private void nextButton_Click(object sender, RoutedEventArgs e)
{
//Load existing list into the savingList (For temporary storage)
savingList = null;
savingList = readSetting("practiceList") != null ? (List<String>)readSetting("practiceList") : new List<String>();
//Remove existing practiceList from IsolatedStorage
settings.Remove("practiceList");
//Add the new practice summary to the savingList
savingList.Add(practiceTextBox.Text.ToString());
//Save the savingList into practiceList in IsolatedStorage
settings.Add("practiceList", savingList);
//Save the summary text itself. Add "-practicesummary" to the end of the name to be able to add it without conflicts with the projectList and it's references
settings.Add(practiceTextBox.Text.ToString() + "-practicesummary", practicesummaryText);
//Save the settings
settings.Save();
MessageBox.Show("next");
}
private void newsummaryPage_Loaded(object sender, RoutedEventArgs e)
{
//Initialize the list
projectList = new List<String>();
try
{
//Load existing list
selectprojectsandsubjectsListBox.Items.Clear();
projectList.Clear();
MessageBox.Show("loaded");
projectList = readSetting("projectList") != null ? (List<String>)readSetting("projectList") : new List<String>();
selectprojectsandsubjectsListBox.ItemsSource = projectList;
}
catch (Exception)
{
//run method CurrentProjectNotEmpty();
}
}
private static object readSetting(string key)
{
return IsolatedStorageSettings.ApplicationSettings.Contains(key) ? IsolatedStorageSettings.ApplicationSettings[key] : null;
}
private void selectprojectsandsubjectsListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
}
private void selectprojectsandsubjectsListBox_Tap(object sender, System.Windows.SizeChangedEventArgs e)
{
//Select a project/subject depending on the amISelectingProjects variable
if (amISelectingProjects.Equals(true))
{
//The user is selecting a project. Get the name from the project and use it to get the subjects
var selectedItem = selectprojectsandsubjectsListBox.SelectedItem as String;
String item = selectedItem;
MessageBox.Show("select");
subjectsList = readSetting(item) != null ? (List<String>)readSetting(item) : new List<String>();
selectprojectsandsubjectsListBox = null;
selectprojectsandsubjectsListBox.ItemsSource = subjectsList;
//Set amISelectingProjects to false so that the user can select subjects next time
amISelectingProjects = false;
//Set the ListBox to multiple selection mode for selecting multiple subjects
selectprojectsandsubjectsListBox.SelectionMode = SelectionMode.Multiple;
//Tell the user what he should do next
MessageBox.Show("The subjects corresponding the the project you selected will now appear in the list. Tap on all the items you want to create a summary of and then press create when you're finished.");
}
else if (amISelectingProjects.Equals(false))
{
//The user is selecting a subject. Select multipe
if (firstSelection.Equals(true))
{
practicesummaryText = selectprojectsandsubjectsListBox.SelectedItem as String;
firstSelection = false;
}
else if (firstSelection.Equals(false))
{
//This is not the first subject that the user selects, therefore add some characters in between
practicesummaryText = practicesummaryText + ". New subject= " + selectprojectsandsubjectsListBox.SelectedItem as String;
}
}
}
}
}
My xaml file:
<phone:PhoneApplicationPage
x:Class="app_name.newsummaryPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="#FF03171B" Loaded="newsummaryPage_Loaded">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" MinHeight="1111"/>
<RowDefinition Height="0*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Grid.Row="0" Margin="12,0,0,0" Height="116" VerticalAlignment="Top">
<TextBlock Text="app name" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="New summary" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<Grid x:Name="newsummaryGrid" Margin="0,116,12,370">
<TextBox x:Name="practiceTextBox" HorizontalAlignment="Left" TextWrapping="Wrap" Width="458" Margin="0,27,0,0" Height="72" VerticalAlignment="Top"/>
<TextBlock HorizontalAlignment="Left" Margin="10,0,0,0" TextWrapping="Wrap" Text="Enter a new name for your summary:" VerticalAlignment="Top"/>
<Button x:Name="nextButton" Content="Create the summary" HorizontalAlignment="Left" Margin="0,553,0,0" VerticalAlignment="Top" Width="456" Click="nextButton_Click"/>
<ListBox x:Name="selectprojectsandsubjectsListBox" Margin="10,99,12,80" SelectionChanged="selectprojectsandsubjectsListBox_SelectionChanged" FontSize="36" Tap="selectprojectsandsubjectsListBox_Tap"/>
</Grid>
<!--ContentPanel - place additional content here-->
</Grid>
</phone:PhoneApplicationPage>
Inner exception:
$exception {System.Windows.Markup.XamlParseException: Failed to assign to property 'System.Windows.UIElement.Tap'. [Line: 32 Position: 172]
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at Knowledge_Organizer.newsummaryPage.InitializeComponent()
at Knowledge_Organizer.newsummaryPage..ctor()} System.Exception {System.Windows.Markup.XamlParseException}
See the output window, it usualy contains useful information about the exception's content.
or when the exception window appears, press break and go to visual studio DEBUG menu, choose windows->locals. the exception should appear in the locals view.
or try to debug and catch the exception, than see it's properties and inner message.

Saving user color settings of a clicked Button in WPF

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

Categories