Changing wpf elements / elements from another class or static method in C #

I have a MainWindow that contains a [statusTextblock] text block that has a binding to the [StatusText] line. StatusTextblock should display combobox results from another window. I pass this data back to mainwindow when it changes in another window, and I made a static method to change the line when this happens.

However, the static nature of all this does not allow me to change my text field element at any time to a new StatusText value.

I was thinking of working around to make changes when the user returned to Mainwindow, but I failed. I tried activating the getfocus and uielement event handler (I feel the second is still a possible fix).

Mainwindow is also always open, if that matters. I also prefer to do something in the code than xaml, but would be grateful for any help.

Any ideas?

MainWindow xaml, then the program input method, then a static event to change statusText

<TextBlock Margin="190,0,0,0" HorizontalAlignment="Right" Name="StatusTextBlock" Text= {Binding}" ></TextBlock> public MainWindow() //Obviously more went here, but it not relevent { StatusTextBlock.DataContext = statusText; } static public void changeStatusText(string status) { statusText = status; } 
+4
source share
1 answer

The problem will be easier to solve when trying to implement the application using the MVVM template.

  • Define a view model class that has the string property StatusText:

     public class MainViewModel : INotifyPropertyChanged { private string _statusText; public event PropertyChangedEventHandler PropertyChanged; public string StatusText { get { return _statusText; } set { if (value == _statusText) return; _statusText = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("StatusText")); } } } 
  • Set the DataContext MainWindow to the instance of MainViewModel:

     public MainWindow //Obviously more went here, but it not relevant { private static MainViewModel _mainViewModel = new MainViewModel(); public MainWindow() { this.DataContext = _mainViewModel; } static public void ChangeStatusText(string status) { _mainViewModel.StatusText = status; } } 
  • Set the data binding to the view model:

      <TextBlock Margin="190,0,0,0" HorizontalAlignment="Right" Name="StatusTextBlock" Text="{Binding StatusText}" ></TextBlock> 
+7
source

Source: https://habr.com/ru/post/1442730/


All Articles