WPF 精修篇 数据绑定到对象
Posted lonelyxmas
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF 精修篇 数据绑定到对象相关的知识,希望对你有一定的参考价值。
原文:WPF 精修篇 数据绑定到对象
数据绑定到对象
首先 我们需要一个对象
- public class Preson
- {
- private string name;
-
- public string Name
- {
- get { return name; }
- set { name = value; }
- }
- private string address;
-
- public string Address
- {
- get { return address; }
- set { address = value; }
- }
- private int age;
-
- public int Age
- {
- get { return age; }
- set { age = value; }
- }
- }
设置依赖属性绑定数据上下文
- public MainWindow()
- {
- InitializeComponent();
- Preson = new Preson() { Name = "慧哥", Address = "大连", Age = 30 };
- DataContext = Preson;
- }
-
-
-
- public Preson Preson
- {
- get { return (Preson)GetValue(PresonProperty); }
- set { SetValue(PresonProperty, value); }
- }
-
- // Using a DependencyProperty as the backing store for Preson. This enables animation, styling, binding, etc...
- public static readonly DependencyProperty PresonProperty =
- DependencyProperty.Register("Preson", typeof(Preson), typeof(MainWindow), new PropertyMetadata(null));
-
- <Grid HorizontalAlignment="Right" Width="517">
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="109*"/>
- <ColumnDefinition Width="112*"/>
- <ColumnDefinition Width="94*"/>
- <ColumnDefinition Width="202*"/>
- </Grid.ColumnDefinitions>
- <Grid.RowDefinitions>
- <RowDefinition Height="24*"/>
- <RowDefinition Height="25*"/>
- <RowDefinition Height="25*"/>
- <RowDefinition Height="86*"/>
- </Grid.RowDefinitions>
- <TextBox HorizontalAlignment="Left" Height="23" Margin="101,27,0,0" Grid.Row="1" TextWrapping="Wrap" Text="{Binding Age,Mode=TwoWay}" VerticalAlignment="Top" Width="120" Grid.ColumnSpan="2" />
- <TextBlock HorizontalAlignment="Left" Margin="41,22,0,0" TextWrapping="Wrap" Text="名字" VerticalAlignment="Top"/>
- <TextBlock HorizontalAlignment="Left" Margin="79,22,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Text="{Binding Name}" Width="30"/>
- <TextBlock HorizontalAlignment="Left" Margin="10,22,0,0" TextWrapping="Wrap" Text="address" VerticalAlignment="Top" Grid.Column="1"/>
- <TextBlock Margin="63.667,22,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Text="{Binding Address}" Grid.Column="1"/>
- <TextBlock HorizontalAlignment="Left" Margin="20,22,0,0" TextWrapping="Wrap" Text="age" VerticalAlignment="Top" Grid.Column="2"/>
- <TextBlock Margin="57,22,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Text="{Binding Age}" Grid.Column="2"/>
- <TextBox HorizontalAlignment="Left" Height="23" Margin="0,17,0,0" Grid.Row="1" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Grid.ColumnSpan="2" Grid.Column="2" />
- </Grid>
前台WPF绑定
这里也可以用 INotifyPropertyChanged 也可以
集合使用ObservableCollenction<对象>
以上是关于WPF 精修篇 数据绑定到对象的主要内容,如果未能解决你的问题,请参考以下文章