![](/img/trans.png)
[英]Databinding ItemsControl (DataTemplate) not updating /only receives values on program start up
[英]Databinding updating with outdated values
我不了解有關數據綁定的以下4點。 不知道我是否得到意想不到的結果(后面代碼中的過時數據),或者這僅僅是我誤解了事情的結果。
有人能解釋為什么會這樣嗎?
所需行為:
我希望在編輯住房數量時更新人數。 最好是動態的,但是失去焦點之后就可以了。 當失去焦點時,島ID 0的值應該是正確的,而不是過時的值。
為了更容易理解 ,帶有3個屏幕的圖片和相關代碼示例。
http://www.mathematik-lehramtsstudium.de/BindingExample.jpg
我的課:
//class for isles
public class isle : INotifyPropertyChanged
{
//Dummyvariables,...
private int _intBauer;
private int _intBauerBev;
//variables
public int intIsleID { set; get; } //isle ID
public string strName { set; get; } //isle name
public int intBauer //housing count
{
set
{
this._intBauer = value;
NotifyPropertyChanged("intBauer"); NotifyPropertyChanged("intBauerBev");
}
get
{
return _intBauer;
}
}
public int intBauerBev //each house hosts 8 people
{
set { this._intBauerBev = value;}
get { return intBauer * 8; }
}
protected void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
LostFocus-Event,用於更新頁面右側
private void textboxHäuser_LostFocus(object sender, RoutedEventArgs e)
{
//Gesamtzahl neu berechnen
listIsles[0].intBauer = 0;
for (int i = 1; i < 10; i++)
{
listIsles[0].intBauer += listIsles[i].intBauer;
}
//hard refresh DataContext, since it does not seem to update itself
//leaving these two lines out of my code changes nothing tho, as expected
gridInfoGesamt.DataContext = "";
gridInfoGesamt.DataContext = listIsles[0];
}
我面臨的問題是在這種情況下事件觸發的順序。 或更准確地說:兩件事同時發生。
TextBox使用“ LostFocus”事件來更新屬性,與我用於更新其他TextBox控件的事件相同。 由於兩者均立即觸發,因此我使用“過時的”數據進行計算,因此,我的UI看起來比一側落后了一步。
為了解決這個問題,我只需要通過在XAML中進行如下綁定來更改TextBox更新屬性的方式即可:
Text="{Binding intBauer, UpdateSourceTrigger=PropertyChanged}"
現在,該屬性在“ LostFocus”之前甚至在“ TextChanged”之前立即更新。 這也使用戶不僅可以在用戶更改值之后還更改值來更新UI。 更清潔,外觀更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.