首页 > 其他分享 >WPF ItemsSource referenced StaticResource

WPF ItemsSource referenced StaticResource

时间:2024-11-03 17:31:04浏览次数:2  
标签:ItemsSource referenced get bmi System set using WPF public

//xaml

 <Window.Resources>
     <local:SizeConverter x:Key="sizeConverter"/>
     <local:BooksData x:Key="booksData"/>
 </Window.Resources>
 <Grid>
     <DataGrid Grid.Row="1"
               x:Name="dg"
               ItemsSource="{StaticResource booksData}"
               CanUserAddRows="False"
               AutoGenerateColumns="False"
               SelectionMode="Extended">
         <DataGrid.Columns>
             <DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
             <DataGridTextColumn Header="ISBN" Binding="{Binding ISBN}"/>
             <DataGridTemplateColumn Header="Image">
                 <DataGridTemplateColumn.CellTemplate>
                     <DataTemplate>
                         <Border 
                             Width="{Binding ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}},
                             Converter={StaticResource sizeConverter}}"
                             Height="{Binding ActualHeight,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}},
                             Converter={StaticResource sizeConverter}}">
                             <Border.Background>
                                 <ImageBrush ImageSource="{Binding ImgSource}" Stretch="Uniform" />
                             </Border.Background>
                         </Border>
                     </DataTemplate>
                 </DataGridTemplateColumn.CellTemplate>
             </DataGridTemplateColumn>
         </DataGrid.Columns>
     </DataGrid>
 </Grid>

public class BooksData : ObservableCollection<Book>
{
    public BooksData()
    {
        var imgs = Directory.GetFiles(@"../../Images");
        int imgsCount = imgs.Count();
        for (int i = 0; i < 100000; i++)
        {
            this.Add(new Book()
            {
                Id = i + 1,
                ISBN = $"ISBN_{Guid.NewGuid().ToString("N")}",
                Name = $"Name_{i + 1}",
                Topic = $"Topic_{i + 1}",
                ImgUrl = $"{imgs[i % imgsCount]}",
                ImgSource = GetImageSource($"{imgs[i % imgsCount]}")
            });
        }
    }

    private ImageSource GetImageSource(string url)
    {
        BitmapImage bmi = new BitmapImage();
        bmi.BeginInit();
        bmi.UriSource = new Uri(url, UriKind.RelativeOrAbsolute);
        bmi.EndInit();
        if (bmi.CanFreeze)
        {
            bmi.Freeze();
        }
        return bmi;
    }
}


public class Book
{
    public int Id { get; set; }

    public string ISBN { get; set; }

    public string Name { get; set; }

    public string Topic { get; set; }

    public string ImgUrl { get; set; }

    public ImageSource ImgSource { get; set; }
}

 

 

 

 

 xaml

//xaml
<Window x:Class="WpfApp27.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"
        WindowState="Maximized"
        xmlns:local="clr-namespace:WpfApp27"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <local:SizeConverter x:Key="sizeConverter"/>
        <local:BooksData x:Key="booksData"/>
    </Window.Resources>
    <Grid>
        <DataGrid Grid.Row="1"
                  x:Name="dg"
                  ItemsSource="{StaticResource booksData}"
                  CanUserAddRows="False"
                  AutoGenerateColumns="False"
                  SelectionMode="Extended">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
                <DataGridTextColumn Header="ISBN" Binding="{Binding ISBN}"/>
                <DataGridTemplateColumn Header="Image">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Border 
                                Width="{Binding ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}},
                                Converter={StaticResource sizeConverter}}"
                                Height="{Binding ActualHeight,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}},
                                Converter={StaticResource sizeConverter}}">
                                <Border.Background>
                                    <ImageBrush ImageSource="{Binding ImgSource}" Stretch="Uniform" />
                                </Border.Background>
                            </Border>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>



using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
using System.IO;

namespace WpfApp27
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class BooksData : ObservableCollection<Book>
    {
        public BooksData()
        {
            var imgs = Directory.GetFiles(@"../../Images");
            int imgsCount = imgs.Count();
            for (int i = 0; i < 100000; i++)
            {
                this.Add(new Book()
                {
                    Id = i + 1,
                    ISBN = $"ISBN_{Guid.NewGuid().ToString("N")}",
                    Name = $"Name_{i + 1}",
                    Topic = $"Topic_{i + 1}",
                    ImgUrl = $"{imgs[i % imgsCount]}",
                    ImgSource = GetImageSource($"{imgs[i % imgsCount]}")
                });
            }
        }

        private ImageSource GetImageSource(string url)
        {
            BitmapImage bmi = new BitmapImage();
            bmi.BeginInit();
            bmi.UriSource = new Uri(url, UriKind.RelativeOrAbsolute);
            bmi.EndInit();
            if (bmi.CanFreeze)
            {
                bmi.Freeze();
            }
            return bmi;
        }
    }


    public class Book
    {
        public int Id { get; set; }

        public string ISBN { get; set; }

        public string Name { get; set; }

        public string Topic { get; set; }

        public string ImgUrl { get; set; }

        public ImageSource ImgSource { get; set; }
    }


    public class SizeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            double d = 0;
            if (double.TryParse(value?.ToString(), out d))
            {
                return d / 2;
            }
            return d;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

 

标签:ItemsSource,referenced,get,bmi,System,set,using,WPF,public
From: https://www.cnblogs.com/Fred1987/p/18523682

相关文章

  • WPF datagrid export command in mvvm and customize delegatecommand inherited from
    publicclassDelCommand:ICommand{publiceventEventHandlerCanExecuteChanged{add{CommandManager.RequerySuggested+=value;}remove{CommandManager.RequerySuggested-=value;......
  • WPF datagrid implement multi select via behavior selectionchanged event in MVVM
    <DataGridItemsSource="{BindingBooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"CanUserAddRows="False"AutoGenerateColumns="False"SelectionMode="Extended">......
  • .NET 平台 WPF 通用权限开发框架 (ABP)
    前言对于大多数.NET后端开发者而言,ABP框架已经相当熟悉,可以轻松进行二次开发,无需重复实现用户角色管理、权限控制、组织管理和多租户等功能。然而,ABP框架主要专注于Web应用,对于桌面端和移动设备的支持较为有限。因此,对于有桌面或移动开发需求的开发者来说,可能需要寻找其他解决方......
  • wpf 数据绑定 数据上下文
    #wpf数据绑定DataContextApp\App\MainWindow.xaml<Windowx:Class="Application.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&q......
  • wpf 数据绑定
    #wpfUI界面数据绑定四种类型ComplicatedButton\ComplicatedButton\MainWindow.xaml<Windowx:Class="WpfApp.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsof......
  • 界面控件DevExpress WPF中文教程:Data Grid——卡片视图概述
    DevExpressWPF拥有120+个控件和库,将帮助您交付满足甚至超出企业需求的高性能业务应用程序。通过DevExpressWPF能创建有着强大互动功能的XAML基础应用程序,这些应用程序专注于当代客户的需求和构建未来新一代支持触摸的解决方案。无论是Office办公软件的衍伸产品,还是以数据为中心......
  • 把代码绑定到WPF中的textblock中
    在WPF中,将数据绑定到TextBlock控件中是一个常见的操作,这样可以动态显示数据源中的数据。以下是如何将数据绑定到TextBlock的步骤:定义数据源:首先,你需要有一个数据源,它可以是一个属性,这个属性需要实现INotifyPropertyChanged接口以便在数据变化时通知UI更新。设置DataContex......
  • WPF重写了ListView的ItemsPanel,改用WrapPanel做容器。不能自动换行问题
    直接上正确代码:1<ListViewx:Name="lv_product"HorizontalContentAlignment="Stretch"ItemsSource="{BindingProducts}"2ScrollViewer.HorizontalScrollBarVisibility="Disabled"ScrollViewer.VerticalScrollB......
  • WPF+MVVM案例实战(十二)- 3D数字翻牌计时实现
    文章目录1、运行效果2、功能实现1、文件创建2、控件代码实现3、控件引用与菜单实现1.引用用户控件2.按钮菜单1、运行效果2、功能实现1、文件创建打开项目Wpf_Examples,在用户控件UserControlLib中创建NumberFoldingCard.xaml文件,在主程序......
  • wpf 触发器 多条件触发器
    wpf触发器多条件触发器<Windowx:Class="GridDemo.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://sch......