[英]Binding textblock text to property on load
我試圖在窗口加載后顯示查詢檢索的記錄數。 這是我在XAML中的內容:
<TextBlock Name="numRecordsAnalyzed_TAtab" TextWrapping="Wrap" Margin="12,0,0,4" Grid.RowSpan="2">
<Run Text="Records Found: " Foreground="{StaticResource Foreground}" FontSize="12"/>
<Run Text="{Binding Numrecords}" Foreground="Red" FontSize="12"/>
</TextBlock>
這是我的c#:
private int numOfrecords = 0;
public event PropertyChangedEventHandler PropertyChanged;
public string Numrecords
{
get { return Convert.ToString(numOfrecords); }
set
{
OnPropertyChanged("NumOfrecords");
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
然后我添加這個來獲取記錄的數量,當我調試時,我看到變量保存了數字,窗口啟動時窗口中顯示的內容都沒有顯示:
numOfrecords = OpenTradesQuery.Count();
我錯過了什么?
您需要引發PropertyChanged
事件以通知GUI進行更新 。
聲明int
類型的屬性,WPF將自動調用屬性上的ToString()
,您不必擔心這一點。
public int Numrecords
{
get { return numOfrecords; }
set
{
if(numOfrecords != value)
{
numOfrecords = value;
OnPropertyChanged("Numrecords");
}
}
}
設置屬性:
Numrecords = penTradesQuery.Count();
您可以在Window / UserControl的構造函數中的InitializeComponent()
之后在代碼中設置DataContext
:
DataContext = this;
此外,您可以在XAML中以root級別設置它,如下所示:
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.