When LastChildFill property of a DockPanel is set true, the last child added occupies the entire unused space.
That works well, until I had to programmatically replace the last child:开发者_Go百科
UIElementCollection children = myDockPanel.Children;
UIElement uie = new myBestControl();
children.RemoveAt(children.Count - 1);
children.Add(uie);
Now, the newly added control no longer fill the space.
How should I fix the problem?
It works for me with this xaml
<DockPanel x:Name="MyDock" LastChildFill="True">
<TextBlock DockPanel.Dock="Left"
MouseDown="TextBlock_MouseDown">Child 1</TextBlock>
<TextBlock DockPanel.Dock="Left">Child 2</TextBlock>
<TextBlock>Child 3</TextBlock>
</DockPanel>
and this code behind
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
UIElementCollection children = MyDock.Children;
Button btn = new Button();
btn.Background = Brushes.LightBlue;
children.RemoveAt(children.Count - 1);
children.Add(btn);
}
when you click text one, the text block is replaced, with a button that has it's back ground set, thus you can see it has happened.
Thanks Simeon. It turns out my confusion came from my misunderstanding of "fill". Apparently, to "fill" does not neccessary mean to occupy the entire space. Instead, the newly added control will be centered if its size is specified.
精彩评论