技术vs艺术

技术是扎实的基本功,艺术是丰富的想象力;技术的突破总是从夸张的想像中开始的。

博客园 首页 新随笔 联系 订阅 管理
 

在 Silverlight 控件的界限之内、现有 Silverlight 内容之上显示内容。

命名空间:  System.Windows.Controls.Primitives
程序集:  System.Windows(在 System.Windows.dll 中)

 

您通常会使用 Popup 类临时显示完成特定任务的内容。例如,您可能会使用弹出项在用户将鼠标指针移到特定控件上时显示帮助信息。Popup 的内容是使用它的 Child 属性设置的,可以是任何 UIElement。将 PopupChild 属性设置为具有 x:Name 特性的控件,会导致在创建 Popup 的多个实例时出现异常。发生这种情况是因为可视化树中不能存在两个同名的项。

您通常会创建一个用户控件来承载弹出内容,但这不是必需的。弹出项将始终显示在 Silverlight 插件的界限之内、现有内容(包括其他弹出控件)之上。应用于 Popup 的父控件的缩放和转换也将应用于 Popup

注意说明:

在某些情况下,通过代码声明控件并将控件添加到 Popup,以及通过代码将 IsOpen 属性设置为 true 而使 Popup 可见,将引起运行时错误。发生这种情况是因为 Popup 的子级位于可视化树中,但 Popup 控件不在可视化树中。若要避免运行时错误,请将 Popup 添加到可视化树中,方法是在 XAML 中声明它或调用 LayoutRoot.Children.Add(popupInstance).

Popup 的 XAML 用法

如前所述,您通常会将 Popup 创建为用户控件的逻辑的一部分。不过,可以在 XAML 中创建一个 Popup。例如,您可能在 XAML ResourceDictionary 中将 Popup 的可视化外观定义为资源。

 

下面的示例演示如何使用 Popup 显示包含一个文本块和一个按钮的边框。为了简明起见,弹出项内容是通过内联方式创建的,但通常您会在单独的用户控件中创建此内容,并使用该控件的实例作为弹出项的子级。

"复制"图像复制代
'
C#  "复制"图像复制代码
// Create the popup object.
Popup p = new Popup();
private void showPopup_Click(object sender, RoutedEventArgs e)
{
    // Create some content to show in the popup. Typically you would 
    // create a user control.
    Border border = new Border();
    border.BorderBrush = new SolidColorBrush(Colors.Black);
    border.BorderThickness = new Thickness(5.0);

    StackPanel panel1 = new StackPanel();
    panel1.Background = new SolidColorBrush(Colors.LightGray);

    Button button1 = new Button();
    button1.Content = "Close";
    button1.Margin = new Thickness(5.0);
    button1.Click += new RoutedEventHandler(button1_Click);
    TextBlock textblock1 = new TextBlock();
    textblock1.Text = "The popup control";
    textblock1.Margin = new Thickness(5.0);
    panel1.Children.Add(textblock1);
    panel1.Children.Add(button1);
    border.Child = panel1;

    // Set the Child property of Popup to the border 
    // which contains a stackpanel, textblock and button.
    p.Child = border;

    // Set where the popup will show up on the screen.
    p.VerticalOffset = 25;
    p.HorizontalOffset = 25;

    // Open the popup.
    p.IsOpen = true;

}

void button1_Click(object sender, RoutedEventArgs e)
{
    // Close the popup.
    p.IsOpen = false;

}

  "复制"图像复制代码
<UserControl x:Class="Popup2.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    FontFamily="Trebuchet MS" FontSize="11"
    Width="200" Height="200">

        <StackPanel x:Name="LayoutRoot" Background="White">
            <Button Width="100" Height="50" x:Name="showPopup" 
            Click="showPopup_Click" Content="Show Popup" />
        </StackPanel>
</UserControl>

 

posted on 2009-11-21 16:08  邓春光  阅读(391)  评论(0编辑  收藏  举报