WPF之多种视图切换

1,View切换,效果呈现

  • 视图1
  • 视图2
  • 视图3

2,在Xaml中添加Listview控件,Combobox控件。

XML 复制代码
<Grid >
        <Grid.RowDefinitions>
            <RowDefinition Height="143*"/>
            <RowDefinition Height="30"/>
        </Grid.RowDefinitions>
        <ListView Grid.IsSharedSizeScope="True" x:Name="listview01" BorderBrush="Red" BorderThickness="2" ></ListView>
        <StackPanel Grid.Row="1" Orientation="Horizontal">
            <TextBlock Text="选择视图模式:" VerticalAlignment="Center"></TextBlock>
            <ComboBox x:Name="combo01" SelectionChanged="combo01_Selected"  MinWidth="150" VerticalContentAlignment="Center">
                <sys:String>GirdView</sys:String>
                <sys:String>ImageDetailView</sys:String>
                <sys:String>ImageView</sys:String>
            </ComboBox>
        </StackPanel>
    </Grid>

3,自定义显示的视图。

cs 复制代码
 [ContentProperty("ItemTemplate")]
    /// <summary>
    /// 自定义的显示视图
    /// </summary>
    public class TitleView : ViewBase
    {
        /// <summary>
        /// ListViewItem数据模板,对应的是ListView的每一项
        /// </summary>
       public DataTemplate ItemTemplate
        {
            get; set;
        }
        /// <summary>
        /// 选中时的背景颜色
        /// </summary>
        public Brush SelectedBackgroundBrush { get; set; } = new SolidColorBrush(Colors.Transparent);
        /// <summary>
        /// 选中时的前景颜色
        /// </summary>
        public Brush SelectedForegroundBrush { get; set; } = new SolidColorBrush(Colors.Black);
        /// <summary>
        /// ListView默认样式资源建,根据此键从Themes文件下资源字典Generic.xaml中获取默认的ListView样式
        /// </summary>
        protected override object DefaultStyleKey
        {
            get
            {
                //根据反射可知只要两个 public ComponentResourceKey(Type typeInTargetAssembly, object resourceId);
                //中typeInTargetAssembly相同,resourceId相同则两个实例的hashcode相同,equal为 True 即两个实例相等
                return new ComponentResourceKey(GetType(),"TitleView");
            }
        }
        /// <summary>
        /// ListViewItem默认样式资源键,根据此键从Themes文件下资源字典Generic.xaml中获取默认的ListViewItem样式
        /// </summary>
        protected override object ItemContainerDefaultStyleKey
        {
            get
            {
                return new ComponentResourceKey(GetType(),"TitleViewItem") ;
            }
        }
    }
  • ListView.View:类型为ViewBase。
  • ViewBase为抽象类,系统只有一个派生类:GridView。
  • ListView.View用于表达ListViewItem中数据呈现的方式,在某一程度上可用ItemTemplate代替。
  • 使用ComponentResourceKey指定资源而不是使用字符串指定资源。

4,定义默认样式。

  • 同自定义无外观控件一样,其默认的样式也必须位于Themes文件夹下的资源字典Generic.xaml
XML 复制代码
 <Style x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:TitleView} ,ResourceId=TitleViewItem}" TargetType="ListViewItem"  >
        <Setter Property="ContentTemplate" Value="{Binding RelativeSource={RelativeSource  Mode=FindAncestor, AncestorType=ListView}, Path=View.ItemTemplate}"></Setter>
        <!--<Setter Property="Grid.IsSharedSizeScope" Value="True"></Setter>-->

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListViewItem">
                    <Border x:Name="Part_Border" Background="Transparent">
                        <ContentPresenter ></ContentPresenter>
                    </Border>
                    
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="true">
                            <Setter TargetName="Part_Border" Property="Background" Value="{Binding RelativeSource={RelativeSource  Mode=FindAncestor, AncestorType=ListView}, Path=View.SelectedBackgroundBrush}"></Setter>
                            <Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource  Mode=FindAncestor, AncestorType=ListView}, Path=View.SelectedForegroundBrush}"></Setter>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:TitleView} ,ResourceId=TitleView}" TargetType="ListView" >
        <Setter Property="ItemsPanel">
            <Setter.Value>
                <ItemsPanelTemplate>
                    <WrapPanel></WrapPanel>
                </ItemsPanelTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListView">
                    <Border Margin="{TemplateBinding Margin}"  BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="5" Background="{TemplateBinding Background}">
                        <ScrollViewer Margin="{TemplateBinding Padding}">
                            <ItemsPresenter></ItemsPresenter>
                        </ScrollViewer>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

5,添加对象资源。

XML 复制代码
<Window.Resources>
        <GridView x:Key="GirdView">
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding ModelName}"></GridViewColumn>
            <GridViewColumn Header="Model" DisplayMemberBinding="{Binding ModelNumber}"></GridViewColumn>
            <GridViewColumn Header="Price" DisplayMemberBinding="{Binding UnitCost,  StringFormat={}{0:C2}}"></GridViewColumn>
        </GridView>
        <local:TitleView x:Key="ImageDetailView" SelectedBackgroundBrush="LightGreen" SelectedForegroundBrush="Red">
            <local:TitleView.ItemTemplate>
                <DataTemplate>
                    <Border BorderBrush="SkyBlue" BorderThickness="2" Margin="5" Padding="5" CornerRadius="5">
                        <Grid >
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="auto">
                                </ColumnDefinition>
                                <ColumnDefinition Width="auto" SharedSizeGroup="c1"></ColumnDefinition>
                            </Grid.ColumnDefinitions>
                            <Image Margin="2" Width="100" Source="/Img/1.jpg" Stretch="Fill"></Image>
                            <StackPanel Grid.Column="1">
                                <TextBlock Text="{Binding ModelName}" FontSize="16" FontWeight="Bold"></TextBlock>
                                <TextBlock Text="{Binding ModelNumber}" ></TextBlock>
                                <TextBlock Text="{Binding UnitCost, StringFormat={}{0:C2}}" ></TextBlock>
                            </StackPanel>
                        </Grid>
                    </Border>
                </DataTemplate>
            </local:TitleView.ItemTemplate>
        </local:TitleView>
        <local:TitleView x:Key="ImageView" SelectedBackgroundBrush="LawnGreen" SelectedForegroundBrush="Blue">
            <DataTemplate>
                <Border BorderBrush="Chocolate" BorderThickness="2" Margin="3" Padding="5">
                    <StackPanel Width="100">
                        <Image Source="/Img/2.jpg" Stretch="Fill"></Image>
                        <TextBlock Text="{Binding ModelName}" TextWrapping="Wrap"></TextBlock>
                    </StackPanel>
                </Border>
            </DataTemplate>
        </local:TitleView>
    </Window.Resources>
  • 在GridView中的GridViewColumn既设置属性DisplayMember也设置属性CellTemplate,那么GridViewColumn将会使用DisplayMember而忽略CellTemplate。

6,代码

cs 复制代码
 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            listview01.ItemsSource = DbStore.DAL.Factory.ProductsDal.QueryAll();
            combo01.SelectedIndex = 0;
        }

        private void combo01_Selected(object sender, RoutedEventArgs e)
        {
            //获取选中的模式
            string str = combo01.SelectedItem.ToString();
            ViewBase view = this.Resources[str] as ViewBase;
            listview01.View = view;
            
        }
    }

7,Demo链接

https://download.csdn.net/download/lingxiao16888/89280022

相关推荐
IT技术分享社区5 小时前
C#实战:使用腾讯云识别服务轻松提取火车票信息
开发语言·c#·云计算·腾讯云·共识算法
月落.6 小时前
WPF的<ContentControl>控件
wpf
就是有点傻6 小时前
WPF中的依赖属性
开发语言·wpf
wangnaisheng6 小时前
【WPF】把一个Window放在左上角/右上角顶格显示
wpf
WineMonk6 小时前
.NET WPF CommunityToolkit.Mvvm框架
.net·wpf·mvvm
月落.6 小时前
WPF中的INotifyPropertyChanged接口
wpf
界面开发小八哥6 小时前
界面控件DevExpress WPF中文教程:Data Grid——卡片视图设置
.net·wpf·界面控件·devexpress·ui开发
平凡シンプル6 小时前
WPF 打包
wpf
VickyJames6 小时前
基于XAML框架和跨平台项目架构设计的深入技术分析
wpf·开源分享·unoplatform·winui3·项目架构
冷眼Σ(-᷅_-᷄๑)10 小时前
WPF缩放动画和平移动画叠加后会发生什么?
wpf·动画