定义DataTemplate 数据模板文件,内容如下
xml
<DataTemplate x:Key="{DataTemplateKey {x:Type VM:TemplateListVM}}" DataType="{x:Type VM:TemplateListVM}">
<Grid Margin="0" Grid.Row="3" Height="50" VerticalAlignment="Top" Visibility="{Binding ShowNoMore, Converter={StaticResource BooleanToVisibilityConverter}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Border Grid.Column="0" Height="1" Margin="60,0,10,0" BorderThickness="1" Name="LeftBorder">
<Border.BorderBrush>
<VisualBrush>
<VisualBrush.Visual>
<Rectangle StrokeDashArray="4 4" Stroke="Gray" StrokeThickness="1"
Width="{Binding ElementName=LeftBorder, Path=ActualWidth}"
Height="2" />
</VisualBrush.Visual>
</VisualBrush>
</Border.BorderBrush>
</Border>
<TextBlock Grid.Column="1" VerticalAlignment="Center" Text="{x:Static loc:MainWindowLoc.NoMoreData}" Style="{StaticResource BodyStyleWhite}" Foreground="{StaticResource BorderGrayBrush}" />
<Border Grid.Column="2" Height="1" Margin="10,0,60,0" BorderThickness="1">
<Border.BorderBrush>
<VisualBrush>
<VisualBrush.Visual>
<Rectangle StrokeDashArray="4 4" Stroke="Gray" StrokeThickness="1"
Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=ActualWidth}"
Height="2" />
</VisualBrush.Visual>
</VisualBrush>
</Border.BorderBrush>
</Border>
</Grid>
</DataTemplate>
虽然显示效果没有问题,但程序运行时两个Width的绑定均会提示绑定失败:
ActualWidth Rectangle.Width Double 找不到源: RelativeSource FindAncestor, AncestorType='System.Windows.Controls.Border', AncestorLevel='1'
或者是找不到LeftBorder。
但如果直接写在userControl里面是没有任何提示的,研究了好久,发现在DataTemplate 需要这样写:
xml
<Grid Margin="0" Grid.Row="3" Height="50" VerticalAlignment="Top" Visibility="{Binding ShowNoMore, Converter={StaticResource BooleanToVisibilityConverter}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.Resources>
<VisualBrush x:Key="leftBorderBrush">
<VisualBrush.Visual>
<Rectangle StrokeDashArray="4 4" Stroke="Gray" StrokeThickness="1" Width="{Binding ElementName=LeftBorder, Path=ActualWidth}" Height="2" />
</VisualBrush.Visual>
</VisualBrush>
<VisualBrush x:Key="RightBorderBrush">
<VisualBrush.Visual>
<Rectangle StrokeDashArray="4 4" Stroke="Gray" StrokeThickness="1" Width="{Binding ElementName=RightBorder , Path=ActualWidth}" Height="2" />
</VisualBrush.Visual>
</VisualBrush>
</Grid.Resources>
<Border Grid.Column="0" Height="1" Margin="60,0,10,0" BorderThickness="1" Name="LeftBorder" BorderBrush="{StaticResource leftBorderBrush}" />
<TextBlock Grid.Column="1" VerticalAlignment="Center" Text="{x:Static loc:MainWindowLoc.NoMoreData}" Style="{StaticResource BodyStyleWhite}" Foreground="{StaticResource BorderGrayBrush}" />
<Border Grid.Column="2" Height="1" Margin="10,0,60,0" BorderThickness="1" Name="RightBorder" BorderBrush="{StaticResource RightBorderBrush}"/>
</Grid>
</Grid>
刚使用wpf做正式项目,暂不清楚两种写法的区别。