我正在重建wpf我的vb6应用程序,该应用程序自2011年以来运行良好。 我的应用处理11个文档。在vb6中,我在MDI中使用了11种形式。
在wpf中,我使用的是Canvas,我称之为Hold。这个画布包含我称为Doc。
的11个FrameworkElement实例Doc提供了为我称为Cell的类绘制形状和文本的方法。 为了在Doc中放置单元格,需要Doc绘制网格。为此我有一个布尔字段(bool _showGrid;),如果真正的Doc绘制网格。
我的问题是Doc FrameworkElement在从xaml调用时不会绘制网格。但是从Window_Loaded它确实。
这是 Doc FrameworkElement :
的一部分public class Doc : FrameworkElement
{
VisualCollection paper;
DrawingVisual cellMaker;
bool _showGrid;
public Doc()
{
paper = new VisualCollection(this);
//SetValue(RenderOptions.EdgeModeProperty, EdgeMode.Aliased);
}
public bool showGrid
{
set
{
_showGrid = value;
if (_showGrid)
{
drawGrid();
}
}
}
private void drawGrid()
{
DrawingVisual grid = new DrawingVisual();
using(DrawingContext dc = grid.RenderOpen())
{
for(int i = 0; i <= Width; i += 18)
{
dc.DrawLine(new Pen(Brushes.OrangeRed, 1), new Point(i, 0), new Point(i, Height));
}
for(int j = 0; j <= Height; j += 18)
{
dc.DrawLine(new Pen(Brushes.OrangeRed, 1), new Point(0, j), new Point(Width, j));
}
dc.Close();
}
paper.Add(grid);
}
这是xaml,其中在showGrid中创建的DocReceipt文件实例设置为true,因为巫婆无效:
<ScrollViewer Grid.Row="1" Grid.Column="0">
<Canvas Name="Hold" Width="21cm" Height="29.7cm" Background="White" Margin="17">
<dc:Doc Name="documentsReceipt"
Width="{Binding Path=ActualWidth,ElementName=Hold}"
Height="{Binding Path=ActualHeight,ElementName=Hold}"
showGrid="True"
Loaded="documentsReceipt_Loaded">
</dc:Doc>
<TextBox Name="txt"
TextChanged="txt_TextChanged"
KeyDown="txt_KeyDown"
PreviewKeyDown="txt_PreviewKeyDown"/>
</Canvas>
</ScrollViewer>
当我从documentReceipt=true
Window_Loaded
时,这是应用
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//documentsReceipt.showGrid = true;
}
这是我启用showGrid时的输出 Window with grid
答案 0 :(得分:1)
通常你实现这样的控件有点不同。首先,您需要ShowGrid
的依赖项属性可绑定。接下来是覆盖OnRender
来绘制形状(或者任何形状)。以下是控件的完整实现:
public class Doc : FrameworkElement
{
public bool ShowGrid
{
get { return (bool)GetValue (ShowGridProperty); }
set { SetValue (ShowGridProperty, value); }
}
public static readonly DependencyProperty ShowGridProperty =
DependencyProperty.Register ("ShowGrid", typeof (bool), typeof (Doc), new FrameworkPropertyMetadata (false, FrameworkPropertyMetadataOptions.AffectsRender));
protected override void OnRender (DrawingContext dc)
{
if (ShowGrid)
{
for (int i = 0; i <= ActualWidth; i += 18)
{
dc.DrawLine (new Pen (Brushes.OrangeRed, 1), new Point (i, 0), new Point (i, Height));
}
for (int j = 0; j <= ActualHeight; j += 18)
{
dc.DrawLine (new Pen (Brushes.OrangeRed, 1), new Point (0, j), new Point (Width, j));
}
}
}
}