I am attempting to create a program in which the User can create multiple profiles. These profiles can be accessed via buttons that appear as each profile is completed.
My problem:
I have no clue how to make the created buttons persist after the program is exited(I need to save the buttons?)
Visually, this is program's process: 1) Enter your information, click continue 2) View a display page of what you entered, click done. 3) This adds a button to the final window, the button of course takes you to 4) Your profile you just created.
After this, the program ends and nothing is saved. I'm fairly new to c# and am quite confused on how to "save" multiple buttons without massively complicating the code. I'm a complete noob to c# and have a little Java experience. Am I going about this correctly? I'm pretty sure its possible but have no idea to go about it.
I will include my code below. I'm working in visual studios 2012. any help would be appreciated!
MainWindow XAML:
<Window x:Class="VendorMain.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">
<Grid>
<Label Content="FirstName" HorizontalAlignment="Left" Margin="63,45,0,0" VerticalAlignment="Top"/>
<Label Content="LastName" HorizontalAlignment="Left" Margin="63,71,0,0" VerticalAlignment="Top"/>
<Label Content="Image" HorizontalAlignment="Left" Margin="63,102,0,0" VerticalAlignment="Top"/>
<Image Name="imgPhoto" Stretch="Fill" Margin="63,133,303,69"></Image>
<Button Name="UploadImageButton" Content="Upload Image" HorizontalAlignment="Left" Margin="130,105,0,0" VerticalAlignment="Top" Width="84" Click="UploadImageButton_Click"/>
<TextBox Name="AssignFirstName" Text="{Binding SettingFirstname}" HorizontalAlignment="Left" Height="23" Margin="130,48,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" />
<TextBox Name="AssignLastName" Text="{Binding SettingLastName}" HorizontalAlignment="Left" Height="23" Margin="130,75,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<Button Name="ContinueToDisplayWindow" Content="Continue" HorizontalAlignment="Left" Margin="409,288,0,0" VerticalAlignment="Top" Width="75" Click="ContinueToDisplayWindow_Click" />
</Grid>
MainWindow Code:
namespace VendorMain
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void UploadImageButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "Select a picture";
op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
"JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"Portable Network Graphic (*.png)|*.png";
if (op.ShowDialog() == true)
{
imgPhoto.Source = new BitmapImage(new System.Uri(op.FileName));
//SettingImage.Source = imgPhoto.Source;
}
}
private void ContinueToDisplayWindow_Click(object sender, RoutedEventArgs e)
{
DisplayPage displaypg = new DisplayPage();
displaypg.DpFirstName.Content = AssignFirstName.Text;
displaypg.DpLastName.Content = AssignLastName.Text;
displaypg.DpImage.Source = imgPhoto.Source;
displaypg.Show();
}
}
}
DisplayPage XAML:
<Window x:Class="VendorMain.DisplayPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DisplayPage" Height="300" Width="525">
<Grid>
<Label Name="DpFirstName" Content="{Binding getFirstNamePermenent}" HorizontalAlignment="Left" Margin="86,55,0,0" VerticalAlignment="Top"/>
<Label Name="DpLastName" Content="{Binding getLastNamePermenent}" HorizontalAlignment="Left" Margin="87,80,0,0" VerticalAlignment="Top"/>
<Image Name="DpImage" HorizontalAlignment="Left" Height="100" Margin="94,111,0,0" VerticalAlignment="Top" Width="100"/>
<Button Name="ButtonizeThisProfile_Button" Content="Done" HorizontalAlignment="Left" Margin="420,238,0,0" VerticalAlignment="Top" Width="75" Click="ButtonizeThisProfile_Button_Click"/>
</Grid>
DisplayPage Code:
namespace VendorMain
{
/// <summary>
/// Interaction logic for DisplayPage.xaml
/// </summary>
public partial class DisplayPage : Window
{
public Button bot1;
public DisplayPage()
{
InitializeComponent();
}
private void newBtn_Click(object sender, RoutedEventArgs e)
{
carryToFinalView();
}
private void ButtonizeThisProfile_Button_Click(object sender, RoutedEventArgs e)
{
UserProfiles uPro = new UserProfiles();
System.Windows.Controls.Button newBtn = new Button();
newBtn.Content = "Person1";
newBtn.Name = "NewProfileButtonAccess";
newBtn.Click += new RoutedEventHandler(newBtn_Click);
uPro.ButtonArea.Children.Add(newBtn);
uPro.Show();
}
public void carryToFinalView()
{
DisplayPage displaypg = new DisplayPage();
displaypg.DpFirstName.Content = DpFirstName.Content;
displaypg.DpLastName.Content = DpLastName.Content;
displaypg.DpImage.Source = DpImage.Source;
displaypg.Show();
}
}
}
UserProfile XAML:
<Window x:Class="VendorMain.UserProfiles"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="UserProfiles" Height="300" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=".8*" />
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="6*"/>
<RowDefinition Height="11*"/>
</Grid.RowDefinitions>
<Label Content="User Profiles: " HorizontalAlignment="Left" Margin="37,47,0,0" VerticalAlignment="Top"/>
<StackPanel Name="ButtonArea" Grid.Column="2" Grid.Row="2">
</StackPanel>
<Button Name="AddAnotherProfileButton" Content="Button" HorizontalAlignment="Left" Margin="35,146,0,0" Grid.Row="1" VerticalAlignment="Top" Width="75" Click="AddAnotherProfileButton_Click"/>
</Grid>
UserProfile Code:
namespace VendorMain
{
public partial class UserProfiles : Window
{
public UserProfiles()
{
InitializeComponent();
}
private void AddAnotherProfileButton_Click(object sender, RoutedEventArgs e)
{
MainWindow mw = new MainWindow();
mw.Show();
}
}
}
As a self proclaimed 'noob', I fear that you won't receive an answer here. I certainly don't have time to repeatedly come back to answer a whole continuing stream of related questions. I also don't have time to provide you with a complete solution. However, I am happy to provide you with sort of 'pseudo code' to at least point you in the right direction... you will have to do a lot of this yourself.
So first things first, as mentioned in a comment, although it is possible, we don't generally save the UI Button objects, but instead we save the data that relates to the user profiles. Therefore, if you haven't done this already, create a User class that has all of the relevant properties. Implement the INotifyPropertyChanged Interface in it and add the SerializableAttribute to the class definition... this will enable you to save this class type as binary data.
Next, in your UI, don't add each Button in xaml... there's a better way. One way or another, add a collection property of type User or whatever your class is called, and set this as the ItemsSource of a ListBox. The idea here is to add a DataTemplate for your User type which will display each of the User items in the collection as a Button:
<DataTemplate x:Key="UserButtonTemplate" DataType="{x:Type DataTypes:User}">
<Button Text="{Binding Name}" Width="75" Click="AddAnotherProfileButton_Click" />
</DataTemplate>
You can find out more about DataTemplates in the Data Templates article.
Implementing this collection allows you to have and display any number of user profiles in your UI, rather than being restricted by screen size as your original example would be.
Now finally, on to saving the data... this can be achieved relatively simply using the following code:
try
{
using (Stream stream = File.Open("ProfileData.bin", FileMode.Create))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter .Serialize(stream, usersList);
}
}
catch { }
One thing to note is that WPF wants us to use the ObservableCollection<T> class when displaying data in the UI, but this class causes problems when serializing data with this method... therefore, you will need to convert your ObservableCollection<T> to a List<T> or similar. However, this can be easily achieved:
List<User> usersList = users.ToList();
You can find out how to de-serialize your data from the C# Serialize List tutorial. You would deserialize (or load the data from the saved file) each time your application starts and re-save the file each time the program closes. You can add an event handler to the Application.Deactivated Event or the Window.Closing which gets called when the application closes, so you can put your code to save the file in there.
Well, I took longer and wrote more than I had expected, so I hope that helps.
Related
I am trying to do a little To-Do app for my school project. I have one problem: i don't know how to delete items both generated by data template in app and those in database.
I've tried accesing items by getting selected item and then deleting it but at some point the id's of those items in db are diffrent from those in the app. I am using SQL server and in my db i have one table with 4 columns: ID(int, auto incremented, primary key), Task(varchar), Descr(varchar), Active(bit). Now i am trying to bind checkbox attribute isChecked to Active of Task class in my app.
this is my xaml code
<Window x:Class="ToDoApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ToDoApp2"
mc:Ignorable="d"
Title="MainWindow" Height="600" Width="400" ResizeMode="NoResize">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="244*"/>
<ColumnDefinition Width="149*"/>
</Grid.ColumnDefinitions>
<TreeView x:Name="TrvMenu" HorizontalAlignment="Left" Height="400" VerticalAlignment="Top" Width="392" Grid.ColumnSpan="2">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:ToDoTask}" ItemsSource="{Binding Tasks}">
<StackPanel Orientation="Horizontal">
<CheckBox Content="{Binding Title}" IsChecked="{Binding active}"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
<TextBox x:Name="TaskTb" HorizontalAlignment="Left" Height="30" Margin="0,400,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="392" Grid.ColumnSpan="2"/>
<TextBox x:Name="DescriptionTb" HorizontalAlignment="Left" Height="80" Margin="0,430,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="392" Grid.ColumnSpan="2"/>
<Button x:Name="CreateBtn" Content="Create New Task" HorizontalAlignment="Left" Margin="0,510,0,0" VerticalAlignment="Top" Width="197" Height="59" Click="Button_Click"/>
<Button x:Name="DeleteBtn" Content="Delete Selected Task" HorizontalAlignment="Left" Margin="197,510,-1,0" VerticalAlignment="Top" Width="196" Height="59" Click="DeleteBtn_Click" Grid.ColumnSpan="2"/>
</Grid>
</Window>
this is the class that represents one task in app
public class ToDoTask
{
public ToDoTask()
{
this.Tasks = new ObservableCollection<ToDoTask>();
}
public string Title { get; set; }
public bool active=true;
public ObservableCollection<ToDoTask> Tasks { get; set; }
}
And this is how i add new tasks to db and app
public MainWindow()
{
InitializeComponent();
SQLCnn init = new SQLCnn();
ObservableCollection<ToDoTask> initList = init.readQuery();
for(int i=0; i < initList.Count; i++)
{
TrvMenu.Items.Add(initList[i]);
}
SQLCnn.connection.Close();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(TaskTb.Text))
{
string value = TaskTb.Text;
string desc = DescriptionTb.Text;
ToDoTask task = new ToDoTask() { Title = value };
task.Tasks.Add(new ToDoTask() { Title = desc });
SQLCnn SQLtask = new SQLCnn();
SQLtask.insertQuery(value, desc);
TrvMenu.Items.Add(task);
}
}
}
As you mentioned in your question you have a problem with Id's generation in your code. You should create a method where you pass all necessary data to create your task and after that, your database should return you back Id of newly created task. So in your case method SQLTask.insertQuery(...) should return id (int value) which is auto-generated by your database. Now you can assign it to newly created object ToDoTask task = new ToDoTask(); task.Id = ... and after that, you can add it to list of tasks. If you do that you will have a valid id value to delete the task from the database. And one more thing, fields are not supported as a binding source so in the ToDoTask class you should change active field to the property if you want to bind it.
In this case, it's all but...
In your project, you can use framework and patterns that will learn you a lot more cool stuff and increase the quality of your code. So to improve working with the database you can use ORM e.g. Entity Framework (https://learn.microsoft.com/en-us/ef/). To separate GUI code from a business logic code, you can use the MVVM pattern. Here you have a lot of options e.g. you can use one of the following projects:
Prism
MVVM Light
Caliburn Micro
To learn more about MVVM please look at this question: MVVM: Tutorial from start to finish?
I got a really tricky and annoying problem with my C# WPF Application. I guess it's not a big deal for a good programmer to solve it, but I don't know how to fix it yet. For school, I have to program an application which depicts a process. So I get Data by an XML-File, have to calculate some values, display them for User Interaction etc. and at the end the output is again a file, which can be processed further.
For that, I got different UserControls, which depicts different modules for example, one for the Data Import, the other one for calculating and displayng values and so on. The Main Window is like the free space or the place-maker on which the different modules are loaded depending on where we are in the process.
My problem now is that the values I calculate in my UserControl won't display in my UI respectively my application and I don't really know why. 0 is the only value which is transferred to the application. Curious about it, is that in the Debugger the values are correct, but in the display itself there is only a 0.
Ok, so I show you now the code of the different files (I'm not the best programmer, so maybe the code is sometimes a bit dirty).
I got a Main UserControl, let's call it UC_Main, and in this UserControl you can switch between 3 different other UserControls depending on which Radiobutton in the UC_Main is checked. (The UC_Main is always displayed, because in this there are only the 3 radio buttons and underneath is a big free space, where the different UserControls 1, 2 and 3 are loaded).
UC_Main.xaml
<UserControl.Resources>
<DataTemplate x:Name="UC1_Template" DataType="{x:Type local:UC1}">
<local:UC1 DataContext="{Binding}" />
</DataTemplate>
<DataTemplate x:Name="UC2_Template" DataType="{x:Type local:UC2}">
<local:UC2 DataContext="{Binding}" />
</DataTemplate>
<DataTemplate x:Name="UC3_Template" DataType="{x:Type local:UC3}">
<local:UC3 DataContext="{Binding}" />
</DataTemplate>
</UserControl.Resources>
<Border Padding="10">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<!-- In the First Row there are the radio buttons in the second the
different UserControls 1, 2 or 3 -->
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<materialDesign:ColorZone Mode="PrimaryMid" Width="400" HorizontalAlignment="Left">
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="2">
<RadioButton x:Name="UC1_radiobutton" Checked="UC1_radiobutton_Checked"
Style="{StaticResource MaterialDesignTabRadioButton}"
Margin="4"
IsChecked="True"
Content="UserControl1" />
<RadioButton x:Name="UC2_radiobutton" Checked="UC2_radiobutton_Checked"
Style="{StaticResource MaterialDesignTabRadioButton}"
Margin="4"
IsChecked="False"
Content="UserControl2" />
<RadioButton x:Name="UC3_radiobutton" Checked="UC3_radiobutton_Checked"
Style="{StaticResource MaterialDesignTabRadioButton}"
Margin="4"
IsChecked="False"
Content="UserControl3" />
</StackPanel>
</materialDesign:ColorZone>
<ContentControl Grid.Row="1" Content="{Binding}" />
</Grid>
</Border>
</UserControl>
UC_Main.xaml.cs
public partial class UC_Main : UserControl
{
public UC_Main()
{
InitializeComponent();
}
private void UC1_radiobutton_Checked(object sender, RoutedEventArgs e)
{
DataContext = new UC1();
}
private void UC2_radiobutton_Checked(object sender, RoutedEventArgs e)
{
DataContext = new UC2();
}
private void UC3_radiobutton_Checked(object sender, RoutedEventArgs e)
{
DataContext = new UC3();
}
}
}
To keep it simple, I'll only show you the Code of UserControl 1, because UC 2 and 3 are pretty the same beside other variables or values.
UC1.xaml
<Border Padding="10">
<StackPanel>
<!-- To keep the example simple, I got 1 Row and 2 Colums; in each
is one TextBox -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<TextBox x:Name="TextBox1" Grid.Column="0" IsTabStop="False"
Text="{Binding Path=variable1, Mode=TwoWay}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
TextAlignment="Center"
Height="25"
Width="85"
Foreground="DarkGray"
IsReadOnly="True" />
<TextBox x:Name="TextBox2" Grid.Column="1" IsTabStop="False"
Text="{Binding Path=variable2, Mode=TwoWay}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
TextAlignment="Center"
Height="25"
Width="85"
Foreground="DarkGray"
IsReadOnly="True" />
</Grid>
</StackPanel>
</Border>
</UserControl>
UC_1.xaml.cs
public partial class UC1 : UserControl
{
public MainWindow Speaker;
public ValueStore vs;
public UC1()
{
InitializeComponent();
Speaker = MainWindow.AppWindow;
vs = new ValueStore();
DataContext = vs;
}
public void calc_data()
{
// I get the data from the data import (XML-File), which is saved in
// a dictionary (strings), converting them to int (so I can do some
// math operations) and save them in my variable.
// UC_Other is a UserControl, where the data import happens
// dict_other is the dictionary, where the data from the import is
// saved
vs.variable1 =
Convert.ToInt32(MainWindow.AppWindow.UC_other.dict_other["0"].Amount);
vs.variable2 =
Convert.ToInt32(MainWindow.AppWindow.UC_other.dict_other["1"].Amount);
}
I call the function calc_data() in an UserControl before, so the data gets calculated and saved in my variables before my UserControl shows up. I declare a new public instance of my UC1 and call the function via UC1.calc_data(); (which is linked to a Button, that is loading my UC_Main).
ValueStore.cs
public class ValueStore : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
private int _variable1;
public int variable1
{
get { return _variable1; }
set { _variable1 = value; OnPropertyChanged("variable1"); }
}
private int _variable2;
public int variable2
{
get { return _variable2; }
set { _variable2 = value; OnPropertyChanged("variable2"); }
}
When I look in the debugger after the method calc_data() is called, the values are correct saved in my ValueStore instance and the TextBoxes are showing me in the Debugger that the correct value is in there (the Debugger says "Name: TextBox1" and "Value: {System.Windows.Controls.TextBox: 100}"; 100 is the value I got from the dictionary), but in my application itself there is only the value 0 displayed.
What I don't really understand is, when I change the type from variable1 to string in my ValueStore.cs and save it in my variable in the method calc_data()(without Convert.ToInt32), it doesn't even show a 0 any more in my application, but in the debugger there is still the value "100".
There are a few things here, but my best guess why your debugging-values are correct while none are updated to the GUI is here:
public partial class UC_Main : UserControl
{
public UC_Main()
{
InitializeComponent();
}
private void UC1_radiobutton_Checked(object sender, RoutedEventArgs e)
{
DataContext = new UC1();
}
private void UC2_radiobutton_Checked(object sender, RoutedEventArgs e)
{
DataContext = new UC2();
}
private void UC3_radiobutton_Checked(object sender, RoutedEventArgs e)
{
DataContext = new UC3();
}
}
You are creating new instances of these classes of the code-behind to the usercontrols. But the usercontrol objects are already created by the UC_Main.xaml so during runtime, you have two objects for example of the UC1 class, one which is your bound to your GUI and one where you store and update your values. The one you see on your GUI doesn't get any values updates, which is why you aren't seeing anything.
I currently can't test the code myself, but from what I can see that is where the issue lies.
Furthermore it is a bit confusing to me, why you are using databinding for code-behind.
(You are using the code-behind of the UC-classes as datacontext for the main class, which is....weird ;) I think in your case no databinding whatsoever is really needed, however if you want to do stuff with databinding you should probably read up on MVVM)
I have a custom input dialog box that request an user's name and a reson (because reasons) for doing a certain action in my application. The user clicks on a button on the main window and the dialog box shows, as it should.
The user then enters his/her name and the reason and clicks ok. The dialog then closes but I ( the program) never receives an answer. Here is my XAML for the input dialog:
<Window x:Class="Sequence_Application_2.GUI.ForcedRackInput"
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"
mc:Ignorable="d"
Title="Forcera Rack" Height="300" Width="300"
WindowStartupLocation="CenterScreen">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="21*"/>
<ColumnDefinition Width="274*"/>
</Grid.ColumnDefinitions>
<TextBox Name="OperatorNameText" HorizontalAlignment="Left" Height="23" Margin="15,36,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Grid.ColumnSpan="2"/>
<Label x:Name="label" Content="Namn:" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Grid.ColumnSpan="2"/>
<Label x:Name="label1" Content="Orsak:" HorizontalAlignment="Left" Margin="10,72,0,0" VerticalAlignment="Top" Grid.ColumnSpan="2"/>
<Border BorderThickness="1" BorderBrush="Black" Grid.ColumnSpan="2" Margin="0,0,0,0.5">
<TextBox Name="ReasonText" Margin="15,98,15,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="116" />
</Border>
<Button Name="OkButton" IsDefault="True" Content="OK" Click="OkButtonPressed" HorizontalAlignment="Left" Margin="26.202,233,0,0" VerticalAlignment="Top" Width="75" Cursor="Arrow" Grid.Column="1"/>
<Button Name="CancelButton" IsCancel="True" Content="Avbryt" Margin="152.202,233,47,0" VerticalAlignment="Top" Cursor="Arrow" Grid.Column="1"/>
</Grid>
</Window>
And here is the "behind code":
namespace Sequence_Application_2.GUI
{
using System.Windows;
public partial class ForcedRackInput : Window
{
public string OperatorName { get { return OperatorNameText.Text; } }
public string ForcedRackReason { get { return ReasonText.Text; } }
public ForcedRackInput()
{
InitializeComponent();
}
private void OkButtonPressed(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
}
}
}
and this is how I call the code (from a model, not a "window class")
public void ForceClosingRack(Flow forcedFlow)
{
var forcedRackWindow = new ForcedRackInput();
string operatorName = "";
string reasonForForced = "";
if( forcedRackWindow.ShowDialog() == true)
{
operatorName = forcedRackWindow.OperatorName;
reasonForForced = forcedRackWindow.ForcedRackReason;
}
} // code jumps from "if(forcedRackWindow.... to this line when ok is clicked in the dialog
Looked for the solution for some time now and I just about to change career
Thanks for your time
My guess is that the problem doesn't lie in the code, which seems to be fine, but in your if statement.
When you run your program in Debug mode it should work as expected.
My guess is that you are assigning the variables operatorName and reasonForForced inside your if statment but they are not used anywhere else in the program and hence the whole if statement is ignored by the compiler and not present when running in Release mode.
A small modification in your code which embeds different behaviour depending on the variable values can prove my guess:
private void Button_Click(object sender, RoutedEventArgs e)
{
var forcedRackWindow = new ForcedWindow();
string operatorName = "foo";
string reasonForForced = "foo";
if (forcedRackWindow.ShowDialog() == true)
{
operatorName = forcedRackWindow.OperatorName;
reasonForForced = forcedRackWindow.ForcedRackReason;
}
if(!operatorName.Equals(reasonForForced))
{
MessageBox.Show("We are not the same");
}
}
I am creating a WPF on which, i have 2 threads. One is the main, and the other one(called PillTimeOutChecker) check some requirements in the main form. If the requirements meet, a new form through the PilleCheckerThread show up in a new thread. The problem is that i am getting this error: Initialization of 'System.Windows.Controls.Button' threw an exception in the initialization of the new form.
This is the method in the main thread, that call the PillCheckerThread:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Thread PillChecker = new Thread(new ThreadStart(PillCheckerThread));
PillChecker.SetApartmentState(ApartmentState.STA);
PillChecker.IsBackground = true;
PillChecker.Name = "PillTimeOutChecker";
PillChecker.Start();
}
This is the content of the PillCheckerThread method:
private void PillCheckerThread()
{
foreach (DataGridObject item in PillList.Items)
{
if(item.DoIt)
{
//Show PillWarning window
Thread PillWarningWindow = new Thread(new ThreadStart(() =>
{
PillWarningWindow pl = new PillWarningWindow(item.PillName, item.AlertTime);
pl.Show();
System.Windows.Threading.Dispatcher.Run();
}));
PillWarningWindow.SetApartmentState(ApartmentState.STA);
PillWarningWindow.IsBackground = true;
PillWarningWindow.Start();
}
}
}
This is the content of the PillWarningWindow:
public partial class PillWarningWindow : Window
{
public PillWarningWindow(string PillName, string CurrentTime)
{
InitializeComponent();
PillNameLbl.Content = PillName;
TimeLbl.Content = CurrentTime;
}
private void CloseBtn_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
This is the xaml of the PillWarningWindow:
<Window x:Class="MedicalReminder.PillWarningWindow"
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:MedicalReminder"
mc:Ignorable="d" Height="300" Width="713.414" ShowInTaskbar="False" Topmost="True" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" WindowStyle="None" Background="Transparent" AllowsTransparency="True">
<Border BorderBrush="Black" CornerRadius="20" Background="DarkCyan">
<Grid>
<Button x:Name="CloseBtn" Content="OK" HorizontalAlignment="Left" Margin="262,239,0,0" VerticalAlignment="Top" Width="179" Click="CloseBtn_Click"/>
<Label x:Name="label" Content="Psssttt !! It's time to take your pill: " HorizontalAlignment="Left" Margin="89,93,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="18"/>
<Label x:Name="PillNameLbl" Content="PillName" HorizontalAlignment="Left" Margin="395,93,0,0" VerticalAlignment="Top" FontSize="18" FontWeight="Bold"/>
<Label x:Name="label2" Content="It's exactly " HorizontalAlignment="Left" Margin="89,132,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="18"/>
<Label x:Name="TimeLbl" Content="12:00" HorizontalAlignment="Left" Margin="195,133,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="17" Width="56"/>
<Label x:Name="label3" Content="you forgot it ??" HorizontalAlignment="Left" Margin="256,132,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="18"/>
</Grid>
</Border>
With a breakpoint at the constructor of the PillWarningWindow i found out that the error start at the InitializeComponent method. Any help is appreciated. Thanks.
If you want to access windows propety you should use Dispatchers.
Because of another thread cannot acces window directly. You can use the Dispatcher when you want to run an operation that will be executed on the UI thread.
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() => PillNameLbl.Content = PillName;
TimeLbl.Content = CurrentTime));
If debugger stops at InitializeComponent method, I'd say there is probably something wrong with your XAML code (which despite of being full of bad practices, doesn't seem to be incorrect). Are you sure your controls don't have style resources defined in any other place? I have had the same error before and it was caused by defining styles in a wrong order.
Try to launch your window directly at the application start instead of launching it from another thread, just to test if it's OK. If it works, then the problem is in the thread management.
I'm learning WPF (moving from Procedural PHP) and have written the following to navigate from 'MainWindow' to 'Page1', where there are no errors with the login credentials, but the local variable 'nav' is always null (hence displaying an error message):
namespace YM_POS_20160229_0949
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void ClickLoginSubmitButton(object sender, RoutedEventArgs e)
{
// Dictionary object is c# equivalent of PHP's 'array["key"] = "value"'
Dictionary<string, string> errMsg = new Dictionary<string, string>();
// declare variables
string varUserName;
string varUserPass;
// define the variables whilst trimming the values passed
varUserName = LoginUsername.Text.Trim();
varUserPass = LoginPassword.Password.Trim();
// ensure something has been submitted & perform validation on the values submitted
// if there are no errors, navigate to the users dashboard (aka Page1)
NavigationService nav = NavigationService.GetNavigationService(new Page1());
// check if the nav variable is populated
if (nav != null)
{
nav.Navigate(nav);
}
else
{
// display an error message to the user advising them an error has occurred and Page1 is not available
MessageBox.Show("An error has occured. unable to proceed to " + nav);
}
}
}
}
Any help greatly appreciated.
Thanks
Newbie Matt
//UI / XAML
<Window x:Class="YM_POS_20160229_0949.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:YM_POS_20160229_0949"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="123*"/>
<ColumnDefinition Width="394*"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="LoginUsername" HorizontalAlignment="Left" Height="23" Margin="56.649,55,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120" Grid.Column="1"/>
<PasswordBox x:Name="LoginPassword" HorizontalAlignment="Left" Height="23" Margin="56.649,100,0,0" Password="Password" VerticalAlignment="Top" Width="120" Grid.Column="1" />
<Button x:Name="LoginSubmitButton" Content="Submit" HorizontalAlignment="Left" Margin="81.649,172,0,0" VerticalAlignment="Top" Width="75" Click="ClickLoginSubmitButton" Grid.Column="1"/>
</Grid>
</DockPanel>
</Window>