TextBlock和TextBox控件的數據綁定可以通過實現自定義類來完成。
編寫自定義類StringToDisplay,監聽TextBlock和TextBox控件的值的變化,StringToDisplay類代碼如下。
public class StringToDisplay : INotifyPropertyChanged
{
privatestring text;
public string Text
{
get{ return text; }
set
{
if(text != value)
{
text = value;
PropertyChanged(this, new PropertyChangedEventArgs("Text"));
}
}
}
public event PropertyChangedEventHandlerPropertyChanged = delegate { };
}
然後在xaml文件中,對TextBlock或TextBox控件的“Text”屬性進行綁定,即“Text="{Binding Text}"”代碼如下。
<TextBlock DockPanel.Dock="Top" Name="callDurationTextBlock" FontWeight="Bold" FontSize="14" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" Height="20" Margin="0,10,0,0" Text="{Binding Text}" />
然後在cs文件中,添加以下代碼。
StringToDisplay callDuration = newStringToDisplay();
callDurationTextBlock.DataContext= callDuration;
之後想要讀取或更改TextBlock或TextBox控件顯示的字符串時,對callDuration.Text進行操作即可,不用直接對控件進行操作,如:
callDuration.Text = "00:00:00";