WPF子窗体:ChildWindow
wpf的子窗体选择有很多种,如最常见的是项目新建窗体(Window)作为子窗体
,或者新建wpf用户控件(UserControl)。而其实利用Xceed.Wpf.Toolkit.dll 可以轻松布局如下:
第一步:引用Xceed.Wpf.Toolkit.dll。
第二步:在XAML引用名称空间:
xmlns:xctk="clr-namespace:Xceed.Wpf.Toolkit.Primitives;assembly=Xceed.Wpf.Toolkit"
xmlns:wpf="clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit"
第三步:布局,XAML如下:
<Window x:Class="ChildWindowDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:xctk="clr-namespace:Xceed.Wpf.Toolkit.Primitives;assembly=Xceed.Wpf.Toolkit" xmlns:wpf="clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit" Title="MainWindow" Height="500" Width="700"> <Grid> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <Button Margin="5" Content="打开子窗体1" Height="40" Width="100" Click="btnOpenChildWindow1_Click"/> <Button Margin="5" Content="打开子窗体2" Height="40" Width="100" Click="btnOpenChildWindow2_Click"/> </StackPanel> <xctk:WindowContainer> <wpf:ChildWindow x:Name="childWindow1" WindowStartupLocation="Center" WindowState="Closed" Caption="子窗体1" Width="300" Height="300"> <StackPanel> <TextBlock Text="这是子窗体1" HorizontalAlignment="Center" VerticalAlignment="Center"/> </StackPanel> </wpf:ChildWindow> <wpf:ChildWindow x:Name="childWindow2" WindowStartupLocation="Center" WindowState="Closed" Caption="子窗体2" Width="500" Height="400"> <StackPanel> <TextBlock Text="这是子窗体2" HorizontalAlignment="Center" VerticalAlignment="Center"/> </StackPanel> </wpf:ChildWindow> </xctk:WindowContainer> </Grid> </Window>
C#后台代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ChildWindowDemo { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void btnOpenChildWindow1_Click(object sender, RoutedEventArgs e) { childWindow1.IsModal = true;//设置为模态窗口 childWindow1.Show(); } private void btnOpenChildWindow2_Click(object sender, RoutedEventArgs e) { childWindow2.IsModal = true; childWindow2.Show(); } } }
总结:有些简单的子窗体,例如要弹出一个列表窗口,而又不想去为此新建一个window,尝试使用ChildWindow,
以及用XAML绑定数据到相应的ChildWindow上,效果很不错