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="{BindingText}"”代码如下。
<TextBlockDockPanel.Dock="Top"Name="callDurationTextBlock"FontWeight="Bold"FontSize="14"Foreground="White"HorizontalAlignment="Center"VerticalAlignment="Center"Height="20"Margin="0,10,0,0"Text="{BindingText}" />
然后在cs文件中,添加以下代码。
StringToDisplay callDuration = newStringToDisplay();
callDurationTextBlock.DataContext= callDuration;
之后想要读取或更改TextBlock或TextBox控件显示的字符串时,对callDuration.Text进行操作即可,不用直接对控件进行操作,如:
callDuration.Text = "00:00:00";