I know that many others questions have been already treated on this subject but i didn't find a proper answer for my case !
I have two classes, "MainWindow" (whiches is the main class) and "Informations" (whiches is a WPF control class). I want to pass the variables "FirstName" and "LastName" from "MainWindow" to the variables "FirstName" and "LastName" of "Informations" in order to reuse them later.
I tried this code, but the values of "FirstName" and "LastName" in "Informations" are null. How can i get it to work ?
MainWindow Class Code :
using System.Windows;
namespace Test
{
public partial class MainWindow : Window
{
#region Set Variables
public string FirstName = "John";
public string LastName = "Smith";
#endregion
public MainWindow()
{
InitializeComponent();
PassVariable();
}
private void PassVariable()
{
Informations informations = new Informations();
informations.FirstName = FirstName;
informations.LastName = LastName;
WrapPanel.Children.Add(informations); // Add Label In WrapPanel But It Return Null
}
}
}
Informations Class Code :
using System.Windows.Controls;
using System.Windows.Media;
namespace Test
{
class Informations : Label
{
#region Set Variables
public string FirstName { get { return FirstName; } set { FirstName = value; } }
public string LastName { get { return LastName; } set { LastName = value; } }
#endregion
public Informations()
{
Foreground = Brushes.White;
FontSize = 14;
Content = FirstName "\n" LastName;
}
}
}
CodePudding user response:
You need to make sure Content
is being updated as soon as FirstName
or LastName
change.
You can do that by updating the Content
in the setters of FirstName
and LastName
. There's just one problem. If you override a property setter, you're also forced to manage the property value yourself. This is done with a so-called backing field:
private string firstName;
public string FirstName {
get => firstName;
set {
firstName = value;
Content = $"{firstName}\n{lastName}";
}
}
// implement the same for `LastName`
CodePudding user response:
You are using FirstName and LastName in the constructor, which is before they have been set by PassVariable(). As a result the Content field will just contain a newline character. Personally, I would pass the two values into the Informations constructor.