WPF如何将Popup附加到像矩形这样的简单UIElement

时间:2013-01-14 22:05:37

标签: wpf popup controls rectangles

我花了几个小时才弄清楚这个问题的答案,所以我想我会写一篇常见问题解答或回答我发现的问题。 (它基于以下线程Binding Textbox IsFocused to Popup IsOpen plus additional conditions

我发现了许多将弹出窗口绑定到切换按钮和其他基于Windows Chrome并具有内置触发器的内容的示例。但在我的应用程序中,我想将弹出窗口绑定到一个带有自定义画笔填充的简单矩形。当用户将鼠标悬停在矩形上时,我找不到一个如何让弹出窗口打开并保持打开的示例。

所以我发布了这个问题,我会立即发布我找到的答案,希望其他人可以从中受益。我也会给那些可以帮助我理解stackoverflow是否允许这样的帖子,或者更好的方式让我理解的人。

编辑1)

我无法自行回答8小时,所以这是工作代码: 以下是如何在基本UIElement上使用弹出窗口的简单示例,如矩形/椭圆/等......

<Grid HorizontalAlignment="Stretch" Height="Auto">
    <Rectangle x:Name="PopupRec"
               Grid.Row="0"
               Width="20" Height="20"
               HorizontalAlignment="Right" 
               Fill="Gray" Margin="0,0,0,10" />
    <Popup x:Name="SortPopup" 
           PlacementTarget="{Binding ElementName=PopupRec}" 
           StaysOpen="False" 
           PopupAnimation="Slide" 
           AllowsTransparency="True">
        <Border Background="White" Padding="15">
            <StackPanel Orientation="Vertical">
                <Button Command="{Binding MyCommand}" CommandParameter="5">5</Button>
                <Button Command="{Binding MyCommand}" CommandParameter="10">10</Button>
                <Button Command="{Binding MyCommand}" CommandParameter="15">15</Button>
                <Button Command="{Binding MyCommand}" CommandParameter="20">20</Button>
            </StackPanel>
        </Border>
        <Popup.Style>
            <Style TargetType="{x:Type Popup}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=PopupRec, Path=IsMouseOver}" Value="True">
                        <Setter Property="IsOpen" Value="True" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding ElementName=SortPopup, Path=IsMouseOver}" Value="True">
                        <Setter Property="IsOpen" Value="True" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Popup.Style>
    </Popup>
</Grid>

只需将其粘贴到window / usercontrol / etc ...

1 个答案:

答案 0 :(得分:3)

我建议以下改进。它会使Popup Style独立于任何元素名称,因此可以通过将其放入Window或UserControl的Resources中来将其用作默认样式。

<Style TargetType="{x:Type Popup}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=IsMouseOver,
                               RelativeSource={RelativeSource Self}}"
                     Value="True">
            <Setter Property="IsOpen" Value="True" />
        </DataTrigger>
        <DataTrigger Binding="{Binding Path=PlacementTarget.IsMouseOver,
                               RelativeSource={RelativeSource Self}}"
                     Value="True">
            <Setter Property="IsOpen" Value="True" />
        </DataTrigger>
    </Style.Triggers>
</Style>

请注意,Rectangle不是“基本的UIElement”。它是Shape,本身就是FrameworkElement