我正在尝试基于 MVVM 模式创建 WP7 应用程序,但我在刷新 TextBlock 的绑定内容时遇到问题。在当前状态下,我需要重新打开页面以刷新内容。我认为这与设置数据上下文有关,但我无法修复它。
ViewModel.cs 中的 PropertyChangedEventHandler
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");
}
}
App.xaml.cs 中的 ViewModel 属性
public partial class App : Application
{
private static ViewModel _viewModel { get; set; }
public static ViewModel ViewModel
{
get { return _viewModel ?? (_viewModel = new ViewModel()); }
}
在 StatusPage.xaml.cs 中设置 DataContext
public partial class Status : PhoneApplicationPage
{
public Status()
{
InitializeComponent();
DataContext = App.ViewModel;
}
StatusPage.xaml 中的绑定
<TextBlock x:Name="TxtStatus" Text="{Binding Path=TxtStatus, Mode=OneWay}" Width="450" TextWrapping="Wrap" HorizontalAlignment="Left" VerticalAlignment="Top" />
更新 1
在 MqttService.cs 中设置 TxtStatus 的值
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;
}
ViewModel.cs 中的 MqttService 属性
private MqttService _mqttService;
public MqttService MqttService
{
get { return _mqttService ?? (_mqttService = new MqttService(this)); }
}
现在我想知道我是否有某种循环引用问题(MqttService-ViewModel)。我不确定,对我来说看起来不错。