簡體   English   中英

更新TextBlock綁定

[英]Updating a TextBlock Binding

我正在開發WP7應用程序,但在更新綁定到屬性的TextBlock遇到了一些麻煩。 我是MVVM和C#的新手,所以我不確定自己做錯了什么。

最后,我解決了這個問題,但是我不明白為什么我的解決方案有效(總是很有趣...),因此,我非常感謝您的指導。

在我的應用程序模型中,我最初有這樣的東西:

// Broken
namespace MyApp.MyModel
{
    public class MetaData : INotifyPropertyChanged
    {
        private StatusType status;
        public StatusType Status
        {
            get { return status; }
            set
            {
                status = value;
                statusMessage = ConvertStatusToSomethingMeaningful(value);
            }
        }

        private string statusMessage;
        public string StatusMessage
        {
            get { return statusMessage; }
            private set
            {
                statusMessage = value;
                // This doesn't work
                NotifyPropertyChanged("StatusMessage");
            }
        }

        ...
    }
}

Status是一個enum ,當由我的應用設置時,它也會同時設置StatusMessage (這是更易於理解的描述,以向用戶顯示)。 我的視圖的TextBlock綁定到StatusMessage ,但不會使用上述代碼進行更新。

但是,如果我將NotifyPropertyChanged("StatusMessage")移到Status ,則我的View的TextBlock像應該的那樣進行更新。 但是,我不明白為什么上面的原始代碼不起作用,為什么這行得通?

// Fixed
namespace MyApp.MyModel
{
    public class MetaData : INotifyPropertyChanged
    {
        private StatusType status;
        public StatusType Status
        {
            get { return status; }
            set
            {
                status = value;
                StatusMessage = ConvertStatusToSomethingMeaningful(value);
                // This works
                NotifyPropertyChanged("StatusMessage");
            }
        }

        public string StatusMessage { get; private set; }

        ...
    }
}

在此先感謝您幫助新手:)

此行中的問題:

 statusMessage = ConvertStatusToSomethingMeaningful(value);

從不調用StatusMessage設置程序(確切地在其中調用NotifyPropertyChanged(“ StatusMessage”))

 StatusMessage = ConvertStatusToSomethingMeaningful(value);

將是正確的選擇

大概我的實現將是下一個:

 namespace MyApp.MyModel
 {
      public class MetaData : INotifyPropertyChanged
      {
           private StatusType status;
           public StatusType Status
           {
                get { return status; }
                set
                {
                     if (status != value)
                     {
                          status = value;
                          NotifyPropertyChanged("Status");
                          NotifyPropertyChanged("StatusMessage");
                     }                
                }
           }

           public string StatusMessage
           {
                get { return ConvertStatusToSomethingMeaningful(status); }
           }

      ...
      }
 }

暫無
暫無

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

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