我在WPF
内有一个动态创建的Canvas
ContentControl
元素(UserControl
中也发生了同样的事情。)每当我尝试设置背景时,要么在程序中创建或以后版本时,背景色将不会绘制(但是我可以在Label
内的Canvas
上设置背景(也可以动态添加)。我拥有创建代码看起来像:
_rootGrid = new Grid();
_rootGrid.Name = "_rootGrid";
_rootGrid.Margin = new Thickness(0);
_rootGrid.HorizontalAlignment = HorizontalAlignment.Stretch;
_rootGrid.VerticalAlignment = VerticalAlignment.Stretch;
_rootGrid.RowDefinitions.Add(new RowDefinition());
_rootGrid.RowDefinitions.Add(new RowDefinition());
_rootGrid.ColumnDefinitions.Add(new ColumnDefinition());
_rootGrid.RowDefinitions[0].Height = new GridLength(24);
_rootGrid.RowDefinitions[1].Height = new GridLength(0, GridUnitType.Star);
_rootGrid.ColumnDefinitions[0].Width = new GridLength(0, GridUnitType.Star);
_headerBlock = new Canvas();
_headerBlock.Name = "_headerBlock";
_headerBlock.SetValue(Grid.RowProperty, 0);
_headerBlock.SetValue(Grid.ColumnProperty, 0);
_headerBlock.PreviewMouseLeftButtonUp += _headerBlock_PreviewMouseLeftButtonUp;
_headerBlock.Background = Brushes.Red;
_title = new Label();
_title.Name = "_title";
_title.Content = "Title";
_title.VerticalAlignment = VerticalAlignment.Center;
_title.HorizontalAlignment = HorizontalAlignment.Left;
_title.FontWeight = FontWeights.Bold;
_title.Background = Brushes.Blue;
_clientBlock = new ScrollViewer();
_clientBlock.Name = "_clientBlock";
_clientBlock.Margin = new Thickness(0);
_clientBlock.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
_clientBlock.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
_clientBlock.SetValue(Grid.RowProperty, 1);
_clientBlock.SetValue(Grid.ColumnProperty, 0);
_clientArea = new Grid();
_clientArea.Name = "_clientArea";
_clientArea.HorizontalAlignment = HorizontalAlignment.Stretch;
_clientArea.VerticalAlignment = VerticalAlignment.Stretch;
_headerBlock.Children.Add(_title);
_rootGrid.Children.Add(_headerBlock);
_clientBlock.Content = _clientArea;
_rootGrid.Children.Add(_clientBlock);
base.Content = _rootGrid;
在ContentControl
构造函数内部调用。据此,我希望标题包含一整行Red
,在文本周围有一个Blue
矩形,但是我得到的只是文本周围的Blue
矩形,其中大部分行都剩下Transparent
(由于根Green
的{{1}}背景而引起注意。)对此的任何帮助将不胜感激,因为它极大地令人沮丧。我正在Grid
上使用6.2
框架的.NET
版本(如果有的话)(我注意到了一些其他奇怪的行为,但之所以要进行动态生成,主要是因为这些{{1 }} s包含许多子元素,并且Windows 7
ContentControl
解析器太坏而无法命名,这实际上使它们毫无用处。)
答案 0 :(得分:1)
解决方案是对ColumnDefinition使用非零宽度:
_rootGrid.ColumnDefinitions[0].Width = new GridLength(1, GridUnitType.Star); // equal to Width="*" in xaml
使用0
时,Canvas具有0 witdh。但是可能会看到蓝色的Label,因为Canvas不会在其边界上剪切内容。
如果您尝试使用零宽度列的网格(var _headerBlock = new Grid();
),将根本不会显示任何内容。