好吧,在你說任何事之前,我知道有多個這樣的帖子,我正在尋找答案几個小時。我是堆棧溢出的新用戶,對於C#和UWP相當新,所以請隨時糾正我。PropertyChanged是空的UWP
我正在爲Windows 10製作UWP商店應用程序。 我正在使用API並且正在連接到服務器。 所有這一切都發生在我的MainPage.xaml
的單獨頁面中,該頁面已加載到Frame
!
我想要做的是顯示string connectionStatus
到MainPage.xaml
(通過<TextBlock/>
),而它在我的LoginPage.xaml.cs
變化(這是MainPage.xaml
框內)。我正在使用INotifyPropertyChanged
。 如果其中任何一個都沒有意義,請發表評論,我會盡力回答。
所以我在我的MainPage.xaml
這個代碼的綁定和<Page.DataContext>
的NotifyChanges
類(這是我的LoginPage.xaml.cs
)。
<Page.DataContext>
<local:NotifyChanges/>
</Page.DataContext>
<TextBlock Text="{Binding ConnectionStatus, Mode=OneWay}" Margin="0,0,10,0" Foreground="LimeGreen" FontWeight="Bold" VerticalAlignment="Center" HorizontalAlignment="Right" FontSize="18"/>
這裏是我的NotifyChanges
類,這是在我的LoginPage.xaml.cs
這是在加載Frame
裏面我MainPage.xaml
:
public class NotifyChanges : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private string connectionStatus = "Disconnected";
public string ConnectionStatus
{
get
{
return connectionStatus;
}
set
{
if (value != connectionStatus)
{
connectionStatus = value;
NotifyPropertyChanged("ConnectionStatus");
}
}
}
}
最後但並非最不重要的,這裏是我的代碼改變在兩個connectionStatus
不同的地方,而連接和連接後。
public async Task Run()
{
NotifyChanges notifyChanges = new NotifyChanges();
try
{
userToken = TokenTextBox.Text;
await client.LoginAsync(TokenType.User, userToken);
var connect = client.ConnectAsync();
notifyChanges.ConnectionStatus = client.ConnectionState.ToString();
await connect;
notifyChanges.ConnectionStatus = client.ConnectionState.ToString();
Frame.Navigate(typeof(ChatPage), userToken);
// Block this task until the program is exited.
await Task.Delay(-1);
}
catch
{
ConnectionErrorTextBlock.Text = "Something went wrong :/ You may want to check the token again!";
}
}
注: 結合似乎工作,因爲你可以看到我已設置的默認值「Disconected」,它被設置,但之後,它將不再改變。 我調試了程序,應用程序進入NotifyChanges定義,但它從不執行通知事件,因爲PropertyChanged
從不會從Null更改。 我錯過了什麼嗎?我的錯誤在別處嗎?提前致謝!
它的工作原理。謝謝你,兄弟。幾個小時一直在嘗試這個。你能解釋爲什麼會發生這種情況嗎? this.DataContext指向Login.xaml.cs的同一頁面。該綁定發生在頁面MainPage中。這是如何運作的 ?謝謝! – KonKarapas
@KonKarapas綁定只是指一個來自DataContext的類,在你的情況下,它是在xaml中創建的。在你的解決方案中,在Run方法中,你已經創建了全新的引用,然後你一直在修改,但它不是來自數據上下文的引用。用戶界面綁定到在xaml中創建的用戶界面。 – Romasz
@KonKarapas請注意,您也可以在頁面的構造函數中分配* NotifyChanges *到一個合適的屬性,然後設置'this.DataContext = propertyNotifyChanges;' - 然後您有一個代碼中的屬性,您可以輕鬆修改而無需投射/創建在xaml中設置DataContext)。你也可以在不設置* DataContext *的情況下使用'x:Bind',但這是另外一個故事 - 有很多關於它的博客/文章。 – Romasz