对于WPF控件 我们都知道自定义模板的话 需要重写ControlTemplate
,
我刚知道 对于拥有Content
属性的控件 还能写ContentTemplate
,ContentTemplate
里面需要用的是 DataTemplate
的标签
<Button Margin="10"
Width="100">
<Button.Content>
<TextBlock Text="s" />
</Button.Content>
<Button.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Background"
Value="DarkCyan" />
<Setter Property="Foreground"
Value="White" />
<Setter Property="FontSize"
Value="16" />
<!--// 自己实现 DataTemplate //-->
<Setter Property="ContentTemplate">
<Setter.Value>
<!--// 只能写一个 要是多个的话 需要在 Resouce 里面设置 //-->
<DataTemplate DataType="{x:Type system:String}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="前缀 - " />
<ContentPresenter Content="{Binding}" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
<!--// ControlTemplate 设置 //-->
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}"
Padding="10,4"
CornerRadius="4">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Resources>
</Button>
从这个按钮引申到ItemControl
先看例子
<ItemsControl ItemsSource="{Binding Items}">
<!--// 设置模板 //-->
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type local:Yuan}">
<Ellipse Width="{Binding R}"
Height="{Binding R}"
Fill="Red" />
</DataTemplate>
<DataTemplate DataType="{x:Type local:Rect}">
<Rectangle Width="{Binding Width}"
Height="{Binding Height}"
Fill="Blue" />
</DataTemplate>
</ItemsControl.Resources>
<!--// 设置坐标 //-->
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left"
Value="{Binding X}" />
<Setter Property="Canvas.Top"
Value="{Binding Y}" />
</Style>
</ItemsControl.ItemContainerStyle>
<!--// 设置容器 //-->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</StackPanel>
ItemTemplate
这个就是按钮例子的Content的内容 但是这个例子使用了多个匹配不同的模板 所以没用写这个 直接在资源文件中写的DataTemplate
ItemsPanel
设置Items的容器ItemContainerStyle
设置Item的样式
在Avlaloina中 应该也差不多 还没有继续研究
参考连接
本文由 jxxxy 创作,采用 知识共享署名4.0 国际许可协议进行许可。
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。