I am developing a Windows phone App and in my MainPage.xaml.cs file I have one private member that is being changed in the overrided method OnNavigateTo(). Although its value is changed, after that in the MainPage constructor its value resets to 0 (It's an int member). I guess that OnNavigateTo() method is being called BEFORE the constructor but if so I would have a nullReferenceException. What can cause that problem?
The OnNavigateTo() Function:
if (NavigationContext.QueryString.ContainsKey("leftDuration"))
{
//Get the selected value from IntroductionPage as a string
var leftRecievedInformation = NavigationContext.QueryString["leftDuration"];
//Convert the string to an enum object
var firstRunLeftChosenDuration = (LensLifetime)Enum.Parse(typeof(LensLifetime), leftRecievedInformation);
//Set the leftDuration value to the model object
_firstRunLeftDuration = getDurationAsNumber(firstRunLeftChosenDuration);
MessageBox.Show(_firstRunLeftDuration + "");
model.Left.LifeTime = _firstRunLeftDuration;
}
My problematic member is the _firstRunLeftDuration value. Although, as you can see, i set the model.Left.LifeTime value, in the MainPage.xaml I still get the default 0 value... It' like completely ignoring this line of code.. I know the code is not particularly clear but I don't think its beneficial to add extra lines of useless code.
Here's the MainPage.xaml.cs file:
public partial class MainPage : PhoneApplicationPage
{
public ContactLensesModel model;
private int _firstRunLeftDuration, _firstRunRightDuration; //Members used for the initialization of the app
public int FirstRunLeftDuration
{
get
{
return _firstRunLeftDuration;
}
set
{
_firstRunLeftDuration = value;
}
}
public int FirstRunRightDuration
{
get
{
return _firstRunRightDuration;
}
set
{
_firstRunRightDuration = value;
}
}
public ContactLensesModel Model
{
get
{
return model;
}
set
{
model = value;
}
}
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
BuildLocalizedApplicationBar();
//Should check if the user starts the app for the first time....
//Create a new model
Model = new ContactLensesModel();
Model.setLeftNewStartingDate();
Model.setRightNewStartingDate();
//Should load the already saved model if the user in not entering for the first time...
//....
//....
loadModel();
//Connect the data Context
leftLensDaysRemaining.DataContext = Model.Left;
rightLensDaysRemaining.DataContext = Model.Right;
}
private int getDurationAsNumber(LensLifetime duration)
{
if (duration.Equals(LensLifetime.Day))
return 1;
else if (duration.Equals(LensLifetime.Two_Weeks))
return 14;
else
return DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//Get the arguments as strings and convert them to an enum, is true only when the user enters app for the first time.
if (NavigationContext.QueryString.ContainsKey("leftDuration"))
{
//Get the selected value from IntroductionPage as a string
var leftRecievedInformation = NavigationContext.QueryString["leftDuration"];
//Convert the string to an enum object
var firstRunLeftChosenDuration = (LensLifetime)Enum.Parse(typeof(LensLifetime), leftRecievedInformation);
//Set the leftDuration value to the model object
FirstRunLeftDuration = getDurationAsNumber(firstRunLeftChosenDuration);
Model.Left.LifeTime = FirstRunLeftDuration;
}
if (NavigationContext.QueryString.ContainsKey("rightDuration"))
{
//Get the selected value from IntroductionPage as a string
var rightRecievedInformation = NavigationContext.QueryString["rightDuration"];
//Convert the string to an enum object
var firstRunRightChosenDuration = (LensLifetime)Enum.Parse(typeof(LensLifetime), rightRecievedInformation);
//Set the leftDuration value to the model object
_firstRunRightDuration = getDurationAsNumber(firstRunRightChosenDuration);
Model.Right.LifeTime = _firstRunRightDuration;
}
}
/// <summary>
/// Loads the model from the isolated Storage
/// </summary>
private void loadModel()
{
//Load the model...
}
private void BuildLocalizedApplicationBar()
{
// Set the page's ApplicationBar to a new instance of ApplicationBar.
ApplicationBar = new ApplicationBar();
// Create a new button and set the text value to the localized string from AppResources.
ApplicationBarIconButton appBarSettingsButton = new ApplicationBarIconButton(new Uri("/Assets/Icons/settingsIcon4.png", UriKind.Relative));
appBarSettingsButton.Text = AppResources.AppBarSettingsButtonText;
appBarSettingsButton.Click += appBarButton_Click;
ApplicationBar.Buttons.Add(appBarSettingsButton);
// Create a new menu item with the localized string from AppResources.
//ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
//ApplicationBar.MenuItems.Add(appBarMenuItem);
}
void appBarButton_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.RelativeOrAbsolute));
}
private void leftButtonChange_Click(object sender, RoutedEventArgs e)
{
model.setLeftNewStartingDate();
}
private void rightChangeButton_Click(object sender, RoutedEventArgs e)
{
model.setRightNewStartingDate();
}
}
}
The OnNavigatedTo method cannot be called before the constructor. The constructor is always executed first. I think your model.Left.LifeTime doesn't raise a PropertyChanged event. Hence, your View won't know you are giving it a value. Therefore it will show the default value of model.Left.Lifetime which is probably 0.
On the other hand, it's hard to tell without seeing the rest of your code.
Related
I'm new to C# and I can't figure out how to reference the value of a variable from one class to another.
It's set to when the button is pressed, it'll take the text in the text box and sets that as "alphaask". Then it instances "alphaanswer" which would tell the label to change its text.
"alphaanswer" will take the value "alphaQuest" and see if its equal to "bob" which then would change the label.
ALL I want to know how to set the value of "alphaQuest" from the value of "alphaask" so the string can check it with "alphaanswer"
public partial class QuestionTab : Form
{
public string alphaask = "null";
public void button1_Click(object sender, EventArgs e)
{
// alphabutton
// Checks if something is in textbox then says bool is true
bool asked = false;
if(textBoxAlpha.Text != "")
{
alphaask = textBoxAlpha.Text;
asked = true;
}
if(asked==true)
{
// If bool is true than instance auxy
var instance = new Alpha();
instance.alphaanswer();
}
}
}
public class Alpha
{
string alphaQuest = // <-- I want to make alphaQuest equal to alphaask
alphaanswer();
public void alphaanswer()
{
if (alphaanswer == bob)
{
//change text in label1
}
}
}
Do these changes
public partial class QuestionTab : Form
{
public string alphaask = "null";
public void button1_Click(object sender, EventArgs e)
{
bool asked = false;
if(textBoxAlpha.Text != "")
{
alphaask = textBoxAlpha.Text;
asked = true;
}
if(asked==true)
{
// If bool is true than instance auxy
var instance = new Alpha();
instance.alphaAnswer(alphaask);
//Here you are sending the current value of alphaAsk to the alphaanswer method.
}
}
}
public class Alpha
{
public void alphaAnswer(string alphaAnswer) //This string receives the value you sent
{
if (alphaAnswer == "bob")
{
//change text in label1
}
}
}
make a contractor in class Alpha with String parameter
public Alpha(String value)
{
}
then when you call it
var instance = new Alpha(alphaask);
instance.show();
In my C# windows form I have 2 forms. I would like to display a collection of strings in a label on a form. When I debug I show the 2 elements in my array but they are not showing in the label I am passing it to. When I hover of toString the data is there but how to I pass it to sender so it will display in the label control I have on my form?
In the snippet of code below to data is in toString but how do I get it from there down to sender.ToString????
public AccountReport_cs(Func<string> toString)
{
this.toString = toString;
}
private void AccountReport_cs_Load(object sender, EventArgs e)
{
label1.Text = sender.ToString();
}
This is another piece of the code that will open form2 where the information should be displayed.
private void reportButton2_Start(object sender, EventArgs e)
{
AccountReport_cs accountReport = new AccountReport_cs(allTransactions.ToString);
accountReport.ShowDialog();
}
Here is the last piece of code and this will show how the data gets to EndOfMonth.
public class Transaction
{
public string EndOfMonth { get; set; }
}
public override List<Transaction> closeMonth()
{
var transactions = new List<Transaction>();
var endString = new Transaction();
endString.EndOfMonth = reportString;
transactions.Add(endString);
return transactions;
}
If you need to send information between forms, the best thing you can do is create a property in the target form and assign the value you want to send before displaying the form; thus you will not need to change the default constructor of the form.
// Destiny form
public partial class FormDestiny : Form {
// Property for receive data from other forms, you decide the datatype
public string ExternalData { get; set; }
public FormDestiny() {
InitializeComponent();
// Set external data after InitializeComponent()
this.MyLabel.Text = ExternalData;
}
}
// Source form. Here, prepare all data to send to destiny form
public partial class FormSource : Form {
public FormSource() {
InitializeComponent();
}
private void SenderButton_Click(object sender, EventArgs e) {
// Instance of destiny form
FormDestiny destinyForm = new FormDestiny();
destinyForm.ExternalData = PrepareExternalData("someValueIfNeeded");
destinyForm.ShowDialog();
}
// Your business logic here
private string PrepareExternalData(string myparameters) {
string result = "";
// Some beautiful and complex code...
return result;
}
}
I'm probably missing something simple, but have been messing with this for a few hours and I cannot get the method to return something not null. When I'm stepping over the process, getDir1 will take the value of the class "swSheetFormatCycle.Form1.FolderUpdate", but getDir1.SwDir remains null so swDir remains null. Will the button method not set swDir or swTemplate the way I'm doing it?
// Get-Set Class
public class FolderUpdate
{
private string swDir;
public string SwDir
{
get {return swDir;}
set {swDir = value;}
}
private string swTemplate;
public string SwTemplate
{
get {return swTemplate;}
set {swTemplate = value;}
}
}
private void btnTemBrow_Click(object sender, EventArgs e)
{
OpenFileDialog tempBrowse = new OpenFileDialog();
DialogResult result = tempBrowse.ShowDialog();
string tempText = tempBrowse.FileName;
txtTemp.Text = tempText;
// Setting the template field
FolderUpdate temUpd = new FolderUpdate();
temUpd.SwTemplate = tempText;
}
private void btnDirBrow_Click(object sender, EventArgs e)
{
FolderBrowserDialog dirBrowse = new FolderBrowserDialog();
DialogResult result = dirBrowse.ShowDialog();
string dirText = dirBrowse.SelectedPath;
txtDir.Text = dirText;
// Setting the directory field
FolderUpdate dirUpd = new FolderUpdate();
dirUpd.SwDir = dirText;
}
// Get the directory set by the button method
swSheetFormatCycle.Form1.FolderUpdate getDir1 = new swSheetFormatCycle.Form1.FolderUpdate();
string swDir = getDir1.SwDir;
// Get the template set by the button method
swSheetFormatCycle.Form1.FolderUpdate getDir2 = new swSheetFormatCycle.Form1.FolderUpdate();
string swTemplate = getDir2.SwTemplate;
Your button events are creating new instances of your FolderUpdate class and then are not doing anything with the object and it is abandoned at the end of the method call.
your "// Get the directory set by the button method" code
is also creating new instances so they will also be null
Attach the FolderUpdate instance to the form itself so that you can reference it.
public class FolderUpdate
{
....
}
public FolderUpdate Folders { get; set; }
private void btnTemBrow_Click(object sender, EventArgs e)
{
...
Folders.SwTemplate = tempText;
}
private void btnDirBrow_Click(object sender, EventArgs e)
{
...
Folders.SwDir = dirText;
}
// Then when you are reading them
var folders = swSheetFormatCycle.Form1.Folders;
string swDir = folders.SwDir;
string swTemplate = folders.SwTemplate;
I have found many answered questions on here explaining how to do this when the objects are created as part of the data source but my list box is just displaying "SharePointXMLBuilder.Farm" (Namespace.class) and not the selected DisplayName?
I dont know what I am doing wrong can anyone help please.
I have a list box with a data source as a databinding control and I am adding my created objects(Farm) to the databinding(farmListBindingSource) which all works fine, I just cant get the list to show the property I want it to.
Form: (loads another form takes input and returns to create object from Farm class)
private void CreateNewFarm_Click(object sender, EventArgs e)
{
FarmInput input = new FarmInput();
input.ShowDialog();
Farm nFarm = new Farm();
nFarm.location = input.inputLocation.ToString();
nFarm.identifier = input.inputType.ToString();
nFarm.environment = input.inputEnvironment.ToString();
this.farmListBindingSource.Add(nFarm);
this.testReturnTextBox.Text = nFarm.friendlyName;
}
private void MainForm_Load(object sender, EventArgs e)
{
this.FarmListBox.DisplayMember = "friendlyName";
this.testReturnTextBox.Text = "Form Loaded....";
}
Class:
namespace SharePointXMLBuilder
{
class Farm
{
private string farmLocation;
private string farmIdentifier;
private string farmEnvironment;
private string farmFriendlyName;
//private List<Server> farmServers;
//properties
public string friendlyName
{
get { return farmFriendlyName; }
set { farmFriendlyName = value; }
}
public string location
{
get { return farmLocation;}
set { farmLocation = value; this.buildFriendlyName(); }
}
public string identifier
{
get { return farmIdentifier; }
set { farmIdentifier = value; this.buildFriendlyName(); }
}
public string environment
{
get { return farmEnvironment; }
set { farmEnvironment = value; this.buildFriendlyName(); }
}
//constructor
public Farm()
{
}
//methods
public void AddServer(string s)
{
Server nServer = new Server(s);
// farmServers.Add(nServer);
}
public void buildFriendlyName()
{
this.friendlyName = this.location + " " + this.identifier + " " + this.environment;
}
}
}
Maybe you are not calling this function: buildFriendlyName() for each object in the list prior to binding?
In your buildfriendlyname() method set your private string farmFriendlyName insted of setting the property value friendlyname
Ok, so I tried to manually add DisplayMember in the designer and it wouldn't hold the value, as soon as I removed the DataSource it allowed DisplayMember to be populated so I changed the CreateNewFarm_Click to add the object to farmListBox.Items and when I re-ran the code it was fine.
It appears that you cannot use DisplayMember if you are pulling the objects from a DataSource.
I've set up a simple form. A ListBox takes values from a list in the 'business object' displaying the Name property and providing the Value property.
In additon the ListBox's SelectedItem property is bound to a property in the same business object.
Using the UI to select a value from the list correctly changes the objects property (checked when the button is clicked) and the correct value is available. So far so good.
However, if the ListBox's SelectedIndex property is changed in the code, then the UI correctly changes as expected but the business property does not change - it would appear to have missed the change event. This is true for both setting in the constructor and in the button event handler (see the code).
What have I missed or what am I doing incorrectly.
(I've only included the code I've written - not VS wizard generated stuff)
class Frequency
{
public String Name { get; set; }
public Int16 Value { get; set; }
public Frequency(String name, Int16 value)
{
Name = name;
Value = value;
}
}
class FrequencyList : System.ComponentModel.BindingList<Frequency>
{
}
class Model
{
public static FrequencyList FrequencyValues = new FrequencyList()
{
new Frequency("Slowest", 100),
new Frequency("Slow", 150),
new Frequency("Medium", 1000),
new Frequency("Fast", 5500),
new Frequency("Fastest", 10000)
};
public Frequency StartFrequency { get; set; }
public void DoStuff()
{
if (StartFrequency == null)
return;
Int16 freq = StartFrequency.Value;
}
}
public partial class Form1 : Form
{
private Model myModel = new Model();
public Form1()
{
InitializeComponent();
// Bind the list to a copy of the static model data
this.listBox1.DataSource = Model.FrequencyValues;
// Bind the control to the model value
this.listBox1.DataBindings.Add("SelectedItem", myModel, "StartFrequency");
// Select the start value
this.listBox1.SelectedIndex = 3;
}
private void button1_Click(object sender, EventArgs e)
{
Int16 f = (Int16)listBox1.SelectedValue;
this.myModel.DoStuff();
int new_index = listBox1.SelectedIndex + 1;
if (new_index >= listBox1.Items.Count)
new_index = 0;
listBox1.SelectedIndex = new_index;
}
}
You don't want the Click event, you want the SelectedIndexChanged event. This will trigger regardless of whether the user or the program instigates the change.