2015-12-15 44 views
3

我试图平铺我的画布相对于像素大小的背景。这是我目前有...WPF以像素为单位的平铺背景

enter image description here

我希望它看起来像这样... 我只是想创建使用代码背景平铺网格。我不想使用PNG或图像文件来创建网格。

enter image description here

<Window x:Class="graph_view.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:local="clr-namespace:graph_view" 
     mc:Ignorable="d" 
     Title="MainWindow" Height="200" Width="200"> 
    <Grid > 
     <Grid.RowDefinitions> 
      <RowDefinition Height="20"/> 
      <RowDefinition Height="*"/> 
     </Grid.RowDefinitions> 

     <TextBox Grid.Row="0" Text="10"></TextBox> 
     <Canvas Grid.Row="1"> 
      <Canvas.Background> 
       <DrawingBrush TileMode="Tile" Viewbox="0,0,20,20" ViewportUnits="RelativeToBoundingBox" AlignmentX="Left" AlignmentY="Top"> 
        <DrawingBrush.Drawing> 
         <GeometryDrawing Brush="sc# 1.0, 0.02, 0.02, 0.02"> 
          <GeometryDrawing.Geometry> 
           <GeometryGroup> 
            <RectangleGeometry Rect="0,0,20,20" /> 
           </GeometryGroup> 
          </GeometryDrawing.Geometry> 
          <GeometryDrawing.Pen> 
           <Pen Thickness="1" Brush="red"/> 
          </GeometryDrawing.Pen> 
         </GeometryDrawing> 
        </DrawingBrush.Drawing> 
       </DrawingBrush> 
      </Canvas.Background> 
     </Canvas> 
    </Grid> 
</Window> 

回答

4
<Canvas> 
    <Canvas.Background> 
     <VisualBrush TileMode="Tile" Stretch="Uniform" Viewport="10,10,10,10" ViewportUnits="Absolute"> 
      <VisualBrush.Visual> 
       <Rectangle Width="10" Height="10" Fill="Black" Stroke="Red"/> 
      </VisualBrush.Visual> 
     </VisualBrush> 
    </Canvas.Background> 
</Canvas> 

enter image description here

变化矩形StrokeThickness值更厚度电网。将ViewPortWidthHeight更改为更大的网格。

<Canvas > 
    <Canvas.Background> 
     <VisualBrush TileMode="Tile" Stretch="Uniform" Viewport="20,20,20,20" ViewportUnits="Absolute"> 
      <VisualBrush.Visual> 
       <Rectangle Width="20" Height="20" Fill="Black" Stroke="Red" StrokeThickness="0.1"/> 
      </VisualBrush.Visual> 
     </VisualBrush> 
    </Canvas.Background> 
</Canvas> 

enter image description here

+0

真棒,正是我想要的。谢谢 – JokerMartini

2

名在XAML网格。

在您的代码隐藏文件中,创建一个循环实际网格宽度并循环网格实际高度的方法。

在宽度循环内,您将在网格中添加一个新列,高度循环将添加一个新行,然后添加一个带有黑色背景和红色边框的新边框。

在init之后调用构造函数中的方法。

只需将宽度传递给提供网格行和列宽度和高度属性的方法即可。

这也可以用XAML很容易地完成。

+0

为什么要所有这些工作时,有在画布本身瓷砖属性。 – JokerMartini

+0

tile属性操纵图像在画布内的显示方式。这个问题是关于不使用图像的具体问题。有很多方法可以在画布中创建网格。我的方法只是一个想法,但与其他元素一样灵活。 WPF的美丽。 – EricM

+0

这是非常真实的。这就是wpf如此强大的原因。你能告诉我如何做你用xaml描述的内容吗? – JokerMartini