I am trying to create a WP7 application based on the MVVM pattern, but I have a problem updating the content of the TextBlock binding. In the current state, I need to open the page again to update the content. I think this is due to setting the data context, but I could not fix it.
PropertyChangedEventHandler Property in ViewModel.cs
public class ViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { if (null != PropertyChanged) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } private string _txtStatus = ""; public string TxtStatus { get { return _txtStatus; } set { _txtStatus = value; NotifyPropertyChanged("TxtStatus"); } }
ViewModel property in App.xaml.cs
public partial class App : Application { private static ViewModel _viewModel { get; set; } public static ViewModel ViewModel { get { return _viewModel ?? (_viewModel = new ViewModel()); } }
Setting DataContext in StatusPage.xaml.cs
public partial class Status : PhoneApplicationPage { public Status() { InitializeComponent(); DataContext = App.ViewModel; }
Binding in StatusPage.xaml
<TextBlock x:Name="TxtStatus" Text="{Binding Path=TxtStatus, Mode=OneWay}" Width="450" TextWrapping="Wrap" HorizontalAlignment="Left" VerticalAlignment="Top" />
UPDATE 1
TxtStatus parameter value in MqttService.cs
public class MqttService { private readonly ViewModel _viewModel; public MqttService(ViewModel viewModel) { _viewModel = viewModel; } private void Log(string log) { _viewModel.TxtStatus = _viewModel.TxtStatus + log; } private void Connect() { _client.Connect(true); Log(MsgConnected + _viewModel.TxtBrokerUrl + ", " + _viewModel.TxtClientId + "\n"); _viewModel.IsConnected = true; }
MqttService property in ViewModel.cs
private MqttService _mqttService; public MqttService MqttService { get { return _mqttService ?? (_mqttService = new MqttService(this)); } }
Now I'm wondering, maybe I have some kind of problem with a circular link (MqttService-ViewModel). I'm not sure this looks good to me.