最近初学WPF,遇到如控件的内容是动态生成的。这时候就需要变量绑定。
简单写下变量绑定的步骤。
如下面的 例子,TextBlock 的内容是动态的,绑定变量StuName。
<TextBlock x:Name="textBlock1" Grid.Column="7" HorizontalAlignment="Left" Margin="68.205,6,0,96" Grid.Row="3" TextWrapping="Wrap" Text="{Binding Path=StuName}" Width="70" Background="#3387FE" Foreground="#FFFFFF" Grid.ColumnSpan="3" />
新建一个Student类并继承。
public class Student: INotifyPropertyChanged { private string stuName; public string StuName { get { return stuName; } set { stuName = value; } } public Student() { } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } }
动态赋值的地方
public partial class MainWindow : Window { private Stduent m_student = null; public void InitStudent() { m_student = new Stduent(); m_student.StuName = "Zhangsan"; this.textBlock1.DataContext = m_student; } public China() { InitializeComponent(); InitStudent(); } }
时间: 2024-11-19 02:02:52