如何将属性绑定到TextBox

时间:2012-03-24 15:29:10

标签: c# silverlight windows-phone-7 silverlight-4.0 silverlight-3.0

我知道,也许这是一个简单的问题,我不知道如何实现这个:

我有我的xaml代码:

<phone:PhoneApplicationPage.Background>
        <ImageBrush ImageSource="/conTgo;component/resources/images/bg_settings.png" Stretch="None"/>
    </phone:PhoneApplicationPage.Background>
    <TextBlock TextWrapping="Wrap" Text="{Binding VersionNumber}" Foreground="{StaticResource PhoneAccentBrush}" FontFamily="Segoe WP Black" FontSize="26.667" TextAlignment="Center" LineHeight="16"/>
</phone:PhoneApplicationPage>

在我的代码背后,我有:

 public string VersionNumber { get; set; }

我怎么能意识到这一点?

2 个答案:

答案 0 :(得分:1)

绑定在datacontext上搜索属性。因此,如果您已将该属性添加到您的页面,那么您必须将您的页面设置为它自己的datacontext。

在页面的构造函数中,在调用“InitializeComponent()”之后,添加:

this.DataContext = this;

这应该可以解决问题。

此方法适用于小型应用。如果您想制作更大,更结构化的应用程序,您可能想了解MVVM模式。

答案 1 :(得分:1)

强烈建议将MVVM模式用于Silverlight开发,并且适用于此类情况以及为单元测试更好地设置代码。

但是,如果您的绑定属性直接驻留在您的控件中并且您希望将其保留在那里,那么您的控件将需要实现INotifyPropertyChanged,以便该属性挂钩到Silverlight(或WPF)的更改通知:

public class YourControl : Control, INotifyPropertyChanged
{

    public string VersionNumber {
        get { return versionNumber; }
        set {
            versionNumber = value;
            NotifyPropertyChanged("VersionNumber");
        }         
    }
    private string versionNumber;

    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(String info) {
        if (PropertyChanged != null) {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}

同样,我肯定会推荐一种MVVM方法。