Home > OS >  Sharing values between different Classes in WPF
Sharing values between different Classes in WPF

Time:09-16

I have a WPF Project where I want to save DataRows from a DataGrid into an "options" class and retrieve those variables in another window.

Thats how I save my Variable from my DataGrid into my "options" Class (mainWindow.xaml.cs):

options.title = Convert.ToString((showEntries.SelectedItem as DataRowView).Row["title"]);

This Variable im saving via a getter and setter (options.cs):

public string Title
        {
            get { return title; }
            set { title = value; }
        }

And now I want to retrieve the saved variable in another window(updateDatabse.xaml):

private void getUpdateEntries()

        {
            Options returnValues = new Options();
            titleBox.Text = returnValues.Title;
        }

My Question is: Why is my textbox "titleBox" empty when running my code.

CodePudding user response:

If the logic of your task does not provide for the creation of several instances of classes (and as far as I understand your explanations, this is so), then you can use the Singlton implementation.
Example:

public class Options
{
    private string title;

    public string Title
    {
        get { return title; }
        set { title = value; }
    }

    private Options() { }

    public static Options Instance { get; } = new Options();
}
Options.Instance.Title = Convert.ToString((showEntries.SelectedItem as DataRowView).Row["title"]);
private void getUpdateEntries()
{
    titleBox.Text = Options.Instance.Title;
}

CodePudding user response:

You mixed things up.

    private void getUpdateEntries()
    
            {
                Options returnValues = new Options();
                returnValues.title = Convert.ToString((showEntries.SelectedItem as DataRowView).Row["title"]);
                titleBox.Text = returnValues.Title;
            }
  • Related