1. 程式人生 > >WPF Binding相關的一些常見方式總結(七)

WPF Binding相關的一些常見方式總結(七)

沒有Source的Binding, 使用DataContext作繫結源;

(實現與案例A一樣的功能):

前端:

<Grid>
        <StackPanel>
            <Button Name="btnTest" Content="測試" Height="100" Click="btnTest_Click"/>
            <TextBlock Name="tblkText" Text="{Binding Path=StuName}" TextAlignment="Center" Height="100"/>
        </StackPanel>
    </Grid>

Model:
public class Student : INotifyPropertyChanged
    {
        private string stuName;
        public string StuName
        {
            get { return stuName; }
            set
            {
                stuName = value;
                if (PropertyChanged != null)
                {
                    this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("StuName"));
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

 

ViewModel:

    public partial class MainWindow : Window
    {
        private Student myStu=new Student();

        public MainWindow()
        {
            InitializeComponent();

            myStu.StuName = "init+ ";
            this.DataContext = myStu;
        }

        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            myStu.StuName += "ab";
        }
    }