WPF小結(三)Binding

1525 ワード

Bindingデータ駆動UI表示、付勢
1.Binding条件
(1)バインド先は依存属性である必要がある(DP)
(2)バインディングソースViewModelはINotifyPropertyChangedインタフェースを実現する必要がある
2.依存属性の定義方法
//     。
        public static readonly DependencyProperty ImageBackgroundProperty =
            DependencyProperty.Register("ImageBackground", typeof(string), typeof(ImageTitle));

        public string ImageBackground
        {
            get { return (string)GetValue(ImageBackgroundProperty); }
            set { SetValue(ImageBackgroundProperty, value); }
        }

3.ViewModel実装INotifyPropertyChangedインタフェース
 /// 
    /// View Model   
    /// 
    public class BaseViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        virtual internal protected void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
public class CorrectQuestionModel : BaseViewModel
    {
        private int questionNum;

        //  
        public int QuestionNum
        {
            get { return questionNum; }
            set
            {
                if (value != questionNum)
                {
                    questionNum = value;
                    OnPropertyChanged("QuestionNum");
                }
            }
        }
    }