我无法ActualWidth
将画布设为任何非零值。我简化了真实场景,并在 VS 中使用了一个新的 WPF 应用程序来获得非零值(和理解)。不幸的是,我只得到零。我觉得我缺少一些基本的 WPF 理解:我对 WPF 不太熟悉。
我复制了MDSN 演示,稍作修改,现在有了
public partial class MainWindow : Window {
private Canvas myCanvas;
public MainWindow()
{
InitializeComponent();
CreateAndShowMainWindow();
}
private void CreateAndShowMainWindow()
{
// Create a canvas sized to fill the window
myCanvas = new Canvas();
myCanvas.Background = Brushes.LightSteelBlue;
// Add a "Hello World!" text element to the Canvas
TextBlock txt1 = new TextBlock();
txt1.FontSize = 14;
txt1.Text = "Hello World!";
Canvas.SetTop(txt1, 100);
Canvas.SetLeft(txt1, 10);
myCanvas.Children.Add(txt1);
// Add a second text element to show how absolute positioning works in a Canvas
TextBlock txt2 = new TextBlock();
txt2.FontSize = 22;
txt2.Text = "Isn't absolute positioning handy?";
Canvas.SetTop(txt2, 200);
Canvas.SetLeft(txt2, 75);
myCanvas.Children.Add(txt2);
Grid content = new Grid();
content.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
content.Children.Add(myCanvas);
this.Content = content;
this.Loaded += MainWindow_Loaded;
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
var canvasRenderWidth = myCanvas.RenderSize.Width;
var canvasActualWidth = myCanvas.ActualWidth;
} //place breakpoint here
我希望画布在加载后与文本框具有相同的 ActualWidth,但在指定的断点处,它为零。请注意,在运行上面的代码时,文本框是可见的。
有人可以告诉我如何使myCanvas.ActualWidth
自动成为textbox.ActualWidth
或告诉我为什么不应该这样做吗?
在我的实际使用场景中,我在 aCanvas
的 a 列中有 a Grid
,其中 columndefinition 的宽度设置为 auto,所以我希望它会随着画布宽度的增加而增加。但是,这失败了,我怀疑这是由于canvas.ActualWidth
为零。