Databinding to a textbox and sharing the object th

2019-09-14 17:37发布

I'm having difficulties with getting a bound textbox to update. I'm still new to WPF development and I must be missing a fundamental concept as I've read nearly everything available on the internet at this point and I'm still confused. Below is my code. First, an overview of what I'm doing to better set the context for my question.

Mainwindow is a Window that contains tabs that load various pages using frame source tags. I believe this might be causing me issues as I'm not sure where the actual object is getting instantiated for each tab, just that the XAML is being loaded.

Scratchpad is a class that contains a textbox, which is going to be updated and used by almost all classes that perform any type of operation to report status and any errors.

Textbox XAML (this is in "ScratchPad_View.xaml" for context)

<TextBox x:Name="scratchMessage" 
             Text="{Binding Path=ScratchMessage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
             HorizontalAlignment="Right" 
             Height="300" 
             Width ="500" 
             TextWrapping="Wrap" 
             VerticalAlignment="Top"/>

Code behind XAML

public partial class ScratchPad : Page
{
    public ScratchPad()
    {
        InitializeComponent();
        ScratchPad_Model ScratchPad_Model = new ScratchPad_Model();
        this.DataContext = ScratchPad_Model;
    }
}

Model Implementation

class ScratchPad_Model : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public string _scratchMessage;
    public string ScratchMessage;
    {
        get
        {
            return _scratchMessage;
        }
        set
        {
            if (value != _scratchMessage)
            {
                _scratchMessage = value;
                OnPropertyChanged("ScratchMessage");
            }
        }
    }
    // Create the OnPropertyChanged method to raise the event 
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Most of this I have cobbled together via responses to other questions on StackOverflow and reading numerous databinding tutorials however it's still not clicking. I'm not sure how to update the contents of the textbox and since I'm loading the page that contains the textbox in the XAML of my mainwindow I'm not sure I'm even referencing the correct object. The mainwindow loads this page in a frame tag, copied below.

<Frame Source="Common/View/ScratchPad_View.xaml" ></Frame>

In the code behind for this XAML, I have the following.

public partial class MainWindow
{
    // Create scratchpad object for logging and status display
    ScratchPad scratchPad = new ScratchPad();

    public MainWindow()
    {
        InitializeComponent();
    }

    private void StartVault(object sender, RoutedEventArgs e)
    {
        // Creates the authentication prompt view object and pass the scratchPad reference for reporting
        authPrompt_View _authPrompt_View = new authPrompt_View(scratchPad);
    }
}

I pass the reference to the ScratchPad object that I created in the initialization of the mainwindow to all classes so that they can update the contents of the textbox, however I haven't had much luck in getting the binding to work. Once it works, I'm still not quite sure how I'm supposed to append text to the textbox. There's probably a great deal of problems here but I'm hoping to fix some of my conceptual problems and get a better understanding of what I'm doing wrong, thanks in advance!

标签: c# wpf xaml mvvm
2条回答
\"骚年 ilove
2楼-- · 2019-09-14 18:18

My understanding is that , You have created the ViewModel for ScratchPad inside the constructor and assigning the DataContext in the same. So, other windows will not have access to the DataContext.

My suggestion is that Maintain a base ViewModel class and inherit the base Viewmodel in all other ViewModel's.

Add ScratchMessage property inside base viewModel. So you can access the ScratchMessage property from other viewModel's too.

 public class BaseViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private string _scratchMessage;

        public string ScratchMessage
        {
            get { return _scratchMessage; }
            set
            {
                _scratchMessage = value;
                this.OnPropertyChanged("ScratchMessage");
            }
        }

        // Create the OnPropertyChanged method to raise the event 
        protected virtual void OnPropertyChanged(string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

    public class ViewModel1 : BaseViewModel
    {
        ViewModel1()
        {
            this.ScratchMessage = "Message";
        }
    }
查看更多
我只想做你的唯一
3楼-- · 2019-09-14 18:38

You can use Application.Properties to set global properties for your project. So probably in SETTER method of textbox bound variable (in your case ScratchMessage), you need to set property in global application properties collection.

Below links explains it very well: https://msdn.microsoft.com/en-us/library/aa348545(v=vs.100).aspx http://www.c-sharpcorner.com/Resources/842/application-properties-in-wpf-and-c-sharp.aspx

查看更多
登录 后发表回答