Windows Phone7 開發教程 - 數據綁定

openkk 12年前發布 | 27K 次閱讀 Windows Phone開發 移動開發 Windows Phone

對于WP7應用程序來說微軟使用了MVC的設計方式,通過數據綁定Data Binding技術可以輕松的將邏輯事務和UI界面連接起來。如果你學習過Silverlight或ASP.NET掌握數據綁定可以跳過本文。對于Windows Phone開發來說,一般為.xaml界面布局文件和對應的.Net代碼實現比如.cs文件,我們就Windows Phone開發必須掌握的數據綁定做個簡單的例子。


 一、數據模型 ViewModel 類必須實現 INotifyPropertyChanged 接口來通知UI數據的改變,關鍵地方代碼Zune123使用了紅色字體標注出來。代碼如下

[DataContract]
public class ViewModel : INotifyPropertyChanged
{
    private string _textBox1Text;
    private bool _checkBox1IsChecked;
    private bool _radioButton1IsChecked;
    private bool _radioButton2IsChecked;
    private double _slider1Value;
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string propertyName)
    {
        if (null != PropertyChanged)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    [DataMember]
    public string TextBox1Text
    {
        get { return _textBox1Text; }
        set
        {
            _textBox1Text = value;
            NotifyPropertyChanged("TextBox1Text");
        }
    }
    [DataMember]
    public bool CheckBox1IsChecked
    {
        get { return _checkBox1IsChecked; }
        set
        {
            _checkBox1IsChecked = value;
            NotifyPropertyChanged("CheckBox1IsChecked");
        }
    }
    [DataMember]
    public double Slider1Value
    {
        get { return _slider1Value; }
        set
        {
            _slider1Value = value;
            NotifyPropertyChanged("Slider1Value");
        }
    }
    [DataMember]
    public bool RadioButton1IsChecked
    {
        get { return _radioButton1IsChecked; }
        set
        {
            _radioButton1IsChecked = value;
            NotifyPropertyChanged("RadioButton1IsChecked");
        }
    }
}

二、界面XAML關聯

  1. TextBlock的內容和剛才ViewModel的關聯,在.xaml文件中代碼如下:

<TextBox Height="72" HorizontalAlignment="Left" Margin="20,0,0,0" Name="textBox1" Text="{Binding TextBox1Text, Mode=TwoWay}" VerticalAlignment="Top" Width="440" />

 2. CheckBox復選控件的數據綁定:

<CheckBox Content="CheckBox" Height="71" Name="checkBox1" Margin="20,0,0,0" IsChecked="{Binding CheckBox1IsChecked, Mode=TwoWay}"/>   

  3. Slider滑塊控件的Data Binding:

<Slider Height="84" Name="slider1" Width="440" Margin="20,0,0,0" Value="{Binding Slider1Value, Mode=TwoWay}"/>

 4. RadioButton單選控件的數據綁定

<RadioButton Content="RadioButton 1" IsChecked="{Binding RadioButton1IsChecked, Mode=TwoWay}" Height="71" Name="radioButton1" GroupName="Numbers"  Margin="20,0,0,0"/>


來源:http://bbs.obaoz.com/thread-11596-1-1.html

 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!