简介:
控件本身就是模板的组合。如果需要灵活发挥控件的功能,需要加入模板。例如ListBox控件的内容和格式。
介绍:
DataTemplate | 数据模板 | |
ControlTemplate | System.Windows.Controls.ControlTemplate | 控件模板 |
ItemsPanelTemplate | System.Windows.Controls.ItemsPanelTemplate | 布局模板 |
public class PersonNP : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string name;
public string Name
{
get { return name; }
set { name = value; Notify(); }
}
private string id;
public string Id
{
get { return id; }
set { id = value;Notify(); }
}
private void Notify([CallerMemberName]string obj ="")
{
if (PropertyChanged != null)
{
this.PropertyChanged (this, new PropertyChangedEventArgs(obj));
}
}
}
public MainWindow()
{
InitializeComponent();
ObservableCollection<PersonNP> ocP = new ObservableCollection<PersonNP>() {
new PersonNP(){Id = "1", Name="test1"},
new PersonNP(){Id = "2", Name="test2"},
};
listBx.ItemsSource = ocP;
}
1.DataTemplate
绑定数据
<Window.Resources>
<DataTemplate x:Key="DataT">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Id}"/>
<TextBlock Text="{Binding Name}" Grid.Column="1"/>
</Grid>
</DataTemplate>
</Window.Resources>
<Grid>
<StackPanel>
<ListBox x:Name="listBx" ItemTemplate="{StaticResource DataT}" ></ListBox>
</StackPanel>
</Grid>
2. ItemsPanelTemplate
更改排列方式
<Window.Resources>
<DataTemplate x:Key="DataT">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Id}"/>
<TextBlock Text="{Binding Name}" Grid.Column="1"/>
</Grid>
</DataTemplate>
<ItemsPanelTemplate x:Key="ItemT">
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</Window.Resources>
<Grid>
<StackPanel>
<ListBox x:Name="listBx" ItemTemplate="{StaticResource DataT}" ItemsPanel="{StaticResource ItemT}"></ListBox>
</StackPanel>
</Grid>
3.ControlTemplate
更改控件显示。
ItemsPresenter,用于指定显示项内容的位置。如果不添加,选项不会显示。
<Window.Resources>
<DataTemplate x:Key="DataT">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Id}"/>
<TextBlock Text="{Binding Name}" Grid.Column="1"/>
</Grid>
</DataTemplate>
<ItemsPanelTemplate x:Key="ItemT">
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
<ControlTemplate TargetType="ListBox" x:Key="ControlT">
<Border x:Name="border" BorderThickness="2" CornerRadius="5">
<ItemsPresenter/>
</Border>
<ControlTemplate.Triggers >
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="BorderBrush" Value="Green"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Window.Resources>
<Grid>
<StackPanel>
<ListBox x:Name="listBx" ItemTemplate="{StaticResource DataT}" Template="{StaticResource ControlT}" ></ListBox>
</StackPanel>
</Grid>