簡體   English   中英

為什么綁定不足以刷新WP7(MVVM)中的UI

[英]Why binding is not enough to refresh UI in WP7 (MVVM)

我正在嘗試基於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)。 我不確定,這對我來說很好看。

WPF .NET4.0您的代碼適合我

所以也許你的Property TxtStatus永遠不會得到一個字符串

_txtStatus ="new status"; // wrong
TxtStatus = "new status"; // right

或者你得到一些干擾你的x:Name="TxtStatus"但這將是一個基於Windows Phone 7的問題

謝謝你們。 Erno de Weerdken2k撰寫關於線程的評論之后,我做了一些研究並發現: 從背景線程通知UI線程 我改變了設置TxtStatus值的方法,現在它運行得很好。 :)

(壞)在MqttService.cs中設置TxtStatus的值

private void Log(string log)
{
    _viewModel.TxtStatus = _viewModel.TxtStatus + log;
}

(好)在MqttService.cs中設置TxtStatus的值

private void Log(string log)
{
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    {
        App.ViewModel.TxtStatus = log + App.ViewModel.TxtStatus;
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM