WPF的工程是由XAML文件和C#文件沟通构成的。C#在工程中主要用于处理逻辑,而XAML则用来在软件界面上显示。很多情况下我们都希望后台的属性改变之后能够在前台的界面上也呈现出来这种变化。常见的这种通知变化的方式有两种,分别是:
1. 使用PropertyChangedEventHandler在属性改变的时候通知用户界面。
2. 使用依赖项属性。
方式一:使用PropertyChangedEventHandler在属性改变的时候通知用户界面。
int _studentAge;
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
int _studentAge;
public int StudentAge
{
get
{
return _studentAge;
}
set
{
_studentAge = value;
OnPropertyChanged("StudentAge"); //这句代码很重要,用其通知前台界面//去改变
}
}
方法二:依赖项属性
public static readonly DependencyProperty StudentAgeProperty = DependencyProperty.Register("StudentAge",
typeof (int),
typeof (StudentData));
public int StudentAge
{
get { return (int)GetValue(StudentAgeProperty); }
set { SetValue(StudentAgeProperty, value); }
}
- 控件模板
控件模板ControlTemplate,有两部分:VistualTree视觉树,即是能看到的外观;Trigger触发器,里面包括外部条件达到某一条件下会引起的响应。
<Button Content="Button" Grid.Row="1" Height="136" HorizontalAlignment="Left" Margin="114,80,0,0" Name="button1" VerticalAlignment="Top" Width="205" >
<Button.Template >
<ControlTemplate >
<Grid >
<Ellipse Name="faceEllipse" Height="50" Width="100" Fill="{TemplateBinding Button.Background}"/>
<TextBlock Name="txtBlock" />
</Grid >
<ControlTemplate.Triggers >
<Trigger Property="Button.IsMouseOver" Value="True">
<Setter Property="Button.Background" Value="blue"/>
</Trigger >
</ControlTemplate.Triggers >
</ControlTemplate >
</Button.Template >
</Button >
- 数据模板
<ListBox Height="202" HorizontalAlignment="Left" Margin="21,12,0,0" Name="listBox1" VerticalAlignment="Top" Width="384" >
<ListBox.ItemTemplate >
<DataTemplate >
<StackPanel Orientation="Horizontal" >
<TextBox Width="60" Text="{Binding Path=Name}"/>
<TextBox Width="60" Text="{Binding Path=ID}"/>
<TextBox Width="60" Text="{Binding Path=Age}"/>
</StackPanel >
</DataTemplate >
</ListBox.ItemTemplate >
</ListBox >