In my program, I have to open a Window with two Pages, and I need to pass some string info to these Pages. I use an attribute on the "parent" Window to do so, which I initialize on the Window constructor.
My problem comes when I try to get the parent Window of one of those Pages on its constructor. I believe I have to do this because I need the string info right at the start, to fill a Combobox.
I try getting the Window this way:
parentWindow = (AsistenteWindow)Window.GetWindow(this);
But when the Page initializes, it gives me a NullReferenceException. I thought the problem was that the Window isn't fully loaded when the Page initialization takes place, but I'm not sure about this.
My Window code is:
public partial class AsistenteWindow : Window
{
#region Atributos
public string Resultado { get; set; } = "";
public string ModeloDispSeleccionado { get; set; } = "";
public string NumeroCluster { get; set; }
public string TextoCluster { get; set; }
#endregion
public AsistenteWindow(string modelo)
{
InitializeComponent();
ModeloDispSeleccionado = modelo;
}
}
The string attributes are the ones I have to access from the Pages.
And my first Page code is:
public partial class AsistenteClusterPage : Page
{
private Dictionary<string, string> dicClusters = new Dictionary<string, string>();
private AsistenteWindow parentWindow;
public AsistenteClusterPage()
{
InitializeComponent();
parentWindow = (AsistenteWindow)Window.GetWindow(this);
try
{
// crea un diccionario con todos los clusters y el texto para mostrar, asegurando que no se repitan
foreach (DataRow mccRow in SQLiteHelper.TramasDataSet.Tables["ModeloClusterCanal"].Rows)
{
if (mccRow["ModeloId"].ToString() == parentWindow.ModeloDispSeleccionado)
{
foreach (DataRow clRow in SQLiteHelper.TramasDataSet.Tables["Cluster"].Rows)
{
if (clRow["ClusterId"].ToString() == mccRow["ClusterId"].ToString()
&& !dicClusters.ContainsKey(clRow["ClusterId"].ToString()))
{
dicClusters.Add(clRow["ClusterId"].ToString(), clRow["ClusterName"] + " (" + clRow["ClusterId"].ToString() + ")");
}
}
}
}
// rellena el ComboBox con los clusters
foreach (KeyValuePair<string, string> keyValue in dicClusters)
{
cbCluster.Items.Add(new ComboBoxItem(keyValue.Value, keyValue.Key));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "/n" + ex.StackTrace);
}
}
}
(I won't post the code for the other Page because it's too long, but I also have to access the string info from there in a similar way, so I guess there will be a problem too)
I also need to be able to close the parent Window from within the Pages.
Is there a better approach for this? Should I not use the attributes in the parent Window, and should I then pass the string info in another way?