WPF数据绑定(二):TextBlock和TextBox的数据绑定

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";


猜你喜欢

转载自blog.csdn.net/wzh0316/article/details/79462164
今日推荐