WPF WebBrowser+TabControl MVVM模式 简单应用 提供源码下载

源代码下载

这个程序是TabControl和Webbrowser的练手小程序

可达到练手目的有:

  • MVVM设计模式的基本使用
  • Binding(包括相对源[RelativeSource]绑定)的基本使用
  • IE COM的基本使用
  • 委托和事件基本使用

程序可实现的效果:

  1. 控制Webbrowser新窗口在TabItem中
  2. TabItem的标头为网页的标题
  3. TabItem可关闭网页
  4. 新开网页自动在前

效果GIF

 

技术要点:

Xaml

<Window x:Class="WPF_WebBrowser_TabControl.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_WebBrowser_TabControl"
        xmlns:data="clr-namespace:WPF_WebBrowser_TabControl.ViewModel"
        mc:Ignorable="d"
        Title="WPF WebBrowser 简易应用" Height="450" Width="800">
    <Window.DataContext>
        <data:WebPageModel/>
    </Window.DataContext>
    <Grid>
        <!--控制TabControl的页面选择要通过SelectedItem的来选择
        注意ViewModel中要实现INotifyPropertyChange接口-->
        <TabControl   SelectedItem="{Binding Index}"  ItemsSource="{Binding WebBrowser}" Grid.ColumnSpan="2"  x:Name="TB">
            <!--此处为TabItem的ItemTemplate-->
            <TabControl.ContentTemplate>
                <DataTemplate>
                    <ContentControl   Content="{Binding Web }"/>
                </DataTemplate>
            </TabControl.ContentTemplate>
            <!--此处为TabItem的Header的模板-->
            <TabControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel   Orientation="Horizontal">
                        <TextBlock Foreground="Red"  Text="{Binding  Title}"/>
                       <!--Button的命令绑定是相对源,使用路径来获取
                        因为TabControl的默认绑定源是Webbrowsr而不是Winodw的Datacontext-->
                        <Button CommandParameter="{Binding   Index}" Command="{Binding RelativeSource={ RelativeSource Mode=FindAncestor,AncestorLevel=1,AncestorType=Window}, Path=DataContext.CloseTab}" 
Height="15" Margin="20,0,0,0"> <Image Source="/WPF WebBrowser TabControl;component/Image/取消.png" /> </Button> </StackPanel> </DataTemplate> </TabControl.ItemTemplate> </TabControl> </Grid> </Window>

 

posted @ 2018-12-05 17:10  ARM830  阅读(1522)  评论(0编辑  收藏  举报