Popup Control VerticalAlignment doesn't “catch”

霸气de小男生 提交于 2019-12-10 15:32:21

问题


I'm using a Popup control, and for some reason its vertical alignment doesn't work as I expect. This is the XAML I have:

    <Grid Width="100" Height="30" >
        <TextBox Text="Hello" />
        <Popup IsOpen="True" VerticalAlignment="Bottom" HorizontalAlignment="Stretch" >
            <Button Content="Hello" />
        </Popup>
    </Grid>

I expected that the Popup's Width would be 100px, the same as it's parent Grid. However, the Button inside the popup behaves as if its HorizontalAlignment is Left, i.e., the Button's width is just enough to allow the word "Hello" inside of it, and I can't figure out why, or how to make it have the same width as the containing Grid.

Thanks!


回答1:


Unfortunately, a Popup is not part of the same visual tree as the rest of the elements in the XAML in which it is defined. It is literally a new window, albeit a very simple and typically small window.

Put another way, the Popup doesn't really participate in the layout of the main window. So changing things like HorizontalAlignment has no effect because that property controls how layout positions and sizes this element relative to its containing element.

This "orphaned element" issue causes no end of problems when dealing with a Popup. Nevertheless, there are tools and techniques to address all the problems that being a separate window introduces.

The first suggestion I can give is to understand the placement properties, PlacementTarget and Placement. You can use these properties for positioning the Popup. You can also use the ElementName syntax of databinding to take care of sizing.

Here is an example of using these techniques in your situation:

<Grid Name="grid" Width="100" Height="30" >
    <TextBox Text="Hello" />
    <Popup IsOpen="True"
           Placement="Bottom"
           PlacementTarget="{Binding ElementName=grid}"
           Width="{Binding ActualWidth, ElementName=grid}">
        <Button Content="Hello" />
    </Popup>
</Grid>


来源:https://stackoverflow.com/questions/6170230/popup-control-verticalalignment-doesnt-catch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!