2017-09-13 7 views
0

私はWPFの初心者ですので、私と一緒に裸にしてください。いくつかのプロパティ(AlertMsg.cs)を持つクラスがあり、INotifyPropertyChangedインターフェイスを使用しています。 xamlを使って、そのクラスの名前空間を私のウィンドウ(MainWindow.xaml)に含めました。 Intellisenseはdatacontextを追加して、xamlだけを使用してそれらのプロパティをウィンドウ要素にバインドするのを助けました。だから私は自分の窓がその特性を知っていることを知っている。 Visual Studioでアプリケーションを実行すると、クラスからのコンストラクタ値が読み込まれます。だから私はそれがプロパティにバインドされていることについてはかなり良い気分です。WPFアプリケーションがINotifyPropertyChangedインターフェイスを使用しているときにxamlのテキストブロックテキストを更新していません。

私は、着信jsonをリッスンする別のクラス(PubNubAlerts.cs)を持っています.Jsonを解析し、それらの値を自分のプロパティクラス(AlertMsg.cs)に設定します。出力ウィンドウでプロパティが変わるのを見ることができるので、この部分もうまく動作します。プロパティが変更されるとPropertyChangedメソッドを実行しても、私のウィンドウ(MainWindow)のUIを見ると、初期化時にロードされたコンストラクタの値はまだ存在します。私は彼らに着信jsonデータで更新してもらいたい。 INotifyPropertyChangedを実装するまでに何が欠けていますか?

MainWindow.xaml

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:Models="clr-namespace:MyApplication.Models" 
     x:Name="AlertPopup" x:Class="MyApplication.MainWindow" 
     Title="AlertMsg" Height="350" Width="525" WindowState="Normal"> 
    <Window.DataContext> 
     <Models:AlertMsg /> 
    </Window.DataContext> 
    <Grid Background="White" Opacity="0.8"> 
     <TabItem Width="500" Height="300" VerticalAlignment="Center" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"> 
      <Frame Source="MainPage.xaml" MinWidth="100" MinHeight="100" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" VerticalAlignment="Center" Width="500" Height="297" FontSize="20" /> 
     </TabItem> 
     <Border Background="{Binding Path=PopUpBackGroundColor, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" BorderBrush="Red" BorderThickness="2" CornerRadius="4" Opacity="0.8" Width="300" Height="80"> 
      <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="22" Text="{Binding Path=MainMessage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Foreground="Black"></TextBlock> 
     </Border> 
    </Grid> 
</Window> 

MainWindow.xaml.cs

using System.Windows; 


namespace MyApplication 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      WindowState = WindowState.Normal; 
      WindowStyle = WindowStyle.ThreeDBorderWindow; 
      Height = 400; 
      Width = 400; 

     } 
    } 
} 

AlertMsg.cs

using System.ComponentModel; 
using System; 

namespace MyApplication.Models 
{ 
    // interface 
    class AlertMsg : INotifyPropertyChanged 
    { 

     public event PropertyChangedEventHandler PropertyChanged = delegate { }; 

     //// constructor, some default values 
     public AlertMsg() 
     { 
      this.MainMessage = "TEXT GOES HERE"; 
      this.PopUpBackGroundColor = "Red"; 
     } 


     // main message property 
     private string mainMessage; 
     public string MainMessage 
     { 
      get 
      { 
       return this.mainMessage; 
      } 
      set 
      { 
       if (value != this.mainMessage) 
       { 
        this.mainMessage = value; 

        System.Diagnostics.Debug.WriteLine("MainMessage is now = " + value); 

        OnPropertyChanged("MainMessage"); 

       } 
      } 
     } 
     //background color property of message 
     private string popupBackGroundColor; 
     public string PopUpBackGroundColor 
     { 
      get 
      { 
       return this.popupBackGroundColor; 
      } 
      set 
      { 

       if (value != this.popupBackGroundColor) 
       { 
        this.popupBackGroundColor = value; 
        System.Diagnostics.Debug.WriteLine("popupbackgroundcolor is now = " + value); 
        OnPropertyChanged("PopUpBackGroundColor"); 
       } 
      } 
     } 


     // call this method on the setter of every property 
     // should change the text of the view 
     private void OnPropertyChanged(string propertyName) 
     { 
      try 
      { 
       // change property 
       if (PropertyChanged != null) 
       { 

        PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
        System.Diagnostics.Debug.WriteLine("Property " + propertyName + " changed."); 

       } 
      } 
      catch (InvalidAsynchronousStateException e) 
      { 
       System.Diagnostics.Debug.WriteLine("Invalid Asynchrounous State Exception" + e.Message); 
      } 
      catch (Exception generalException) 
      { 
       System.Diagnostics.Debug.WriteLine("Error OnPropertyChanged: " + propertyName + " " + generalException.Message); 
      } 

     } 

    } 
} 

PubNubAlerts.cs(私にJSONを供給し、サードパーティ。あなたができます私のプロパティを更新していることを知っているのでこれにあまり気にする必要はありませんが、私はそれをとにかくケースに入れました)

using System; 
using Newtonsoft.Json.Linq; 
using PubnubApi; 
using MyApplication.Models; 


namespace MyApplication 
{ 
    public class PubNubAlerts 
    { 
     static public Pubnub pubnub; 
// hardcoded values for testing 
     static public string channel = "TestChannel"; 
     static public string authKey = "xxxxxxxxxx"; 
     static public string subscribeKey = "xxxxx-xxxxxx-xxxxx-xxxxxxxx"; 
     static public string channelGroup = ""; 
     static public string mainBody; 

     AlertMsg alertMsg = new AlertMsg(); 

     public void PubNubSubscribe() 
     { 
      // config 
      PNConfiguration config = new PNConfiguration() 
      { 
       AuthKey = authKey, 
       Secure = false, 
       SubscribeKey = subscribeKey, 
       LogVerbosity = PNLogVerbosity.BODY 
      }; 
      try 
      { 

       pubnub = new Pubnub(config); 

       // add listener 
       pubnub.AddListener(new SubscribeCallbackExt(
       (pubnubObj, message) => { 
     // grab data from json and parse 
     System.Diagnostics.Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(message)); 
        string jsonMessage = pubnub.JsonPluggableLibrary.SerializeToJsonString(message); 
        dynamic data = JObject.Parse(jsonMessage); 
     // update alertmsg properties with json from pubnub 
     alertMsg.MainMessage = data.Message.mainmessage; 
        alertMsg.PopUpBackGroundColor = data.Message.popupbackgroundcolor; 


       }, 
       (pubnubObj, presence) => { 
        System.Diagnostics.Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(presence)); 
       }, 
       (pubnubObj, status) => { 
        System.Diagnostics.Debug.WriteLine("{0} {1} {2} ", status.Operation, status.Category, status.StatusCode); 
       } 
       )); 

       System.Diagnostics.Debug.WriteLine("Running subscribe()"); 

       // subscribe 
       pubnub.Subscribe<object>() 
       .WithPresence() 
       .Channels(channel.Split(',')) 
       .ChannelGroups(channelGroup.Split(',')) 
       .Execute(); 
      } 
      catch (Exception e) 
      { 
       System.Diagnostics.Debug.WriteLine("FAILED TO SUBSCRIBE: " + e.Message); 
      } 

     } 

    } 
} 

MainWindow Image

答えて

3

あなたはAlertMsgの2つの異なるインスタンスを持っています。

あなたがここにあなたの窓のデータコンテキストとしてのインスタンスをインスタンス化している「MainWindow.xaml」で

<Window.DataContext> 
    <Models:AlertMsg /> 
</Window.DataContext> 

そして「PubNubAlerts.cs」であなたがライン19の周りのインスタンスをインスタンス化されています

AlertMsg alertMsg = new AlertMsg(); 

ウィンドウのDataContextPubNubAlertsに渡す必要があります。または、PubNubAlertsがウィンドウのDataContextを使用してバインドするインスタンスを公開する必要があります。

+0

はい、何かの2つの異なるインスタンスが動作しないでしょう。私はpubnub内のプロパティを作成し、それを公開し、pubnubプロパティにdatacontextを切り替え、MainWindowの更新を開始しました。どうもありがとうございました。 – jackT