我正在尝试创建基于 MVVM 模式的 WP7 应用程序,但我在刷新 TextBlock 的绑定(bind)内容时遇到问题。 在当前状态下,我需要重新打开页面以刷新内容。我认为这与设置数据上下文有关,但我无法修复它。
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 中绑定(bind)
<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)。我不确定,我觉得不错。
最佳答案
你的代码在 WPF
.NET4.0
中对我来说工作正常
所以也许你的属性 TxtStatus
永远不会得到一个字符串
_txtStatus ="new status"; // wrong
TxtStatus = "new status"; // right
或者您的 x:Name="TxtStatus"
受到一些干扰,但这将是基于 Windows-Phone-7 的问题
关于c# - 为什么绑定(bind)不足以刷新 WP7 (MVVM) 中的 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17102905/