我正在尝试基于MVVM模式创建WP7应用程序,但我在刷新TextBlock的绑定内容方面遇到了问题。 在当前状态下,我需要重新打开页面才能刷新内容。 我认为这与设置数据上下文有关,但我无法解决它。
在ViewModel.cs中使用PropertyChangedEventHandler。
在 StatusPage.xaml.cs 中设置 DataContext
在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");
}
}
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()); }
}
在 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)。我不确定,但我认为看起来还不错。
, UpdateSourceTrigger=PropertyChanged
- WiiMaxxTxtStatus
是否在 UI 线程中更新? - ken2k