簡體   English   中英

如何將屬性綁定到TextBox

[英]How can I bind a property to a TextBox

我知道,也許這是一個簡單的問題,我不知道如何實現這個:

我有我的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; }

我怎么能意識到這一點?

綁定將在您的datacontext上搜索該屬性。 因此,如果您已將屬性添加到頁面中,則必須將頁面設置為自己的datacontext。

在頁面的構造函數中,在調用“InitializeComponent()”之后,添加:

this.DataContext = this;

這應該夠了吧。

這種方法適用於小型應用。 如果您想制作更大,更結構化的應用程序,您可能想了解MVVM模式。

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方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM