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 >