首页 > 其他分享 >WPF Element Width Height is percent of Parent element via converter ,converterparameter

WPF Element Width Height is percent of Parent element via converter ,converterparameter

时间:2024-09-19 21:13:28浏览次数:1  
标签:via converter Parent Windows object System value using public

//converter
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace WpfApp380
{
    public class SizeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return System.Convert.ToDouble(value)*System.Convert.ToDouble(parameter);
        }

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


 <Window.Resources>
     <local:SizeConverter x:Key="sizeConverer"/>
 </Window.Resources>


 <Image Source="{Binding ImgUrl}" 
        Width="{Binding Converter={StaticResource sizeConverer},
     Path=ActualWidth,
     RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}},
     ConverterParameter=0.5}"
        Height="{Binding Converter={StaticResource sizeConverer},
     Path=ActualHeight,
        RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}},
     ConverterParameter=0.5}"/>

 

 

 

 

 

 

//conveter
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace WpfApp380
{
    public class SizeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return System.Convert.ToDouble(value)*System.Convert.ToDouble(parameter);
        }

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


//xaml
<Window x:Class="WpfApp380.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:WpfApp380" 
        mc:Ignorable="d" 
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:BookVM/>
    </Window.DataContext>
    <Window.Resources>
        <local:SizeConverter x:Key="sizeConverer"/>
    </Window.Resources>
    <Grid>
        <ListBox ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                 VirtualizingPanel.IsContainerVirtualizable="True"
                 VirtualizingPanel.VirtualizationMode="Recycling"
                 VirtualizingPanel.CacheLength="100"
                 VirtualizingPanel.CacheLengthUnit="Item">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Image Source="{Binding ImgUrl}" 
                               Width="{Binding Converter={StaticResource sizeConverer},
                            Path=ActualWidth,
                            RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}},
                            ConverterParameter=0.5}"
                               Height="{Binding Converter={StaticResource sizeConverer},
                            Path=ActualHeight,
                               RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}},
                            ConverterParameter=0.5}"/>
                        <TextBlock Text="{Binding Name}" FontSize="50" Foreground="Red"
                                   FontWeight="ExtraBlack"
                                   VerticalAlignment="Center"
                                   HorizontalAlignment="Center"/>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>


//xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
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;
using System.Collections.ObjectModel;

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

    public class BookVM : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public BookVM()
        {
            InitData();
        }

        private void InitData()
        {
            var imgsList = Directory.GetFiles(@"../../Images");
            if (imgsList != null && imgsList.Any())
            {
                int imgsCount = imgsList.Count();
                BooksCollection = new ObservableCollection<Book>();
                for(int i=0;i<1000000;i++)
                {
                    BooksCollection.Add(new Book()
                    {
                        Id = i,
                        Name = $"Name_{i}",
                        Title=$"Title_{i}",
                        Topic=$"Topic_{i}",
                        ISBN=$"ISBN_{i}",
                        ImgUrl = imgsList[i%imgsCount]
                    });
                }
            }
        }

        private ObservableCollection<Book> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                if(value!=booksCollection)
                {
                    booksCollection = value;
                    OnPropertyChanged(nameof(BooksCollection));
                }
            }
        }
    }


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

        public string Name { get; set; }

        public string Title { get; set; }

        public string Topic { get; set; }

        public string ISBN { get; set; }

        public string ImgUrl { get; set; }
    }
}

 

标签:via,converter,Parent,Windows,object,System,value,using,public
From: https://www.cnblogs.com/Fred1987/p/18421381

相关文章

  • Imitating Language via Scalable Inverse Reinforcement Learning
    本文是LLM系列文章,针对《ImitatingLanguageviaScalableInverseReinforcementLearning》的翻译。通过可扩展的逆向强化学习模仿语言摘要1引言2方法3实验4相关工作5讨论6结论摘要大多数语言模型训练都建立在模仿学习的基础上。它涵盖了预训练、监......
  • General OCR Theory: Towards OCR-2.0 via a Unified End-to-end Model
    摘要传统的OCR系统(OCR-1.0)越来越无法满足人们对智能处理人造光学字符的需求。在本文中,我们将所有人造光学信号(例如,普通文本、数学/分子公式、表格、图表、乐谱,甚至是几何形状)统称为“字符”,并提出了通用OCR理论以及一个优秀的模型,即GOT,以促进OCR-2.0的到来。GOT拥有5.8亿参......
  • Trivial, standard-layout, POD, and literal types
    转自:Trivial,standard-layout,POD,andliteraltypeshttps://learn.microsoft.com/en-us/cpp/cpp/trivial-standard-layout-and-pod-types?view=msvc-170微软这篇文章写的很详尽,也配有代码实例Trivial,standard-layout,POD,andliteraltypes    Thetermlayoutre......
  • WPF overlay on the icon in the taskbar via TaskbarItemInfo
    <Windowx:Class="WpfApp372.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft......
  • [WPF]XAML中使用IMultiValueConverter实现Command的多参数传参
    对ICommand进行多参数传参问题如何对ICommand传入多个参数?背景最近在做一个WPF的开发,有多个相近的功能写了不同的Command,因为要对应不同的对象。因为是CtrlCV,显得代码有点冗赘不够优雅,但是ICommand又只能接受一个参数。思路使用MultiBinding,对CommandParameter进行绑定,然后......
  • Google Aviator Evaluator 使用入门(一)
    Aviator Evaluator 使用入门(一)https://www.yuque.com/boyan-avfmj/aviatorscript/tvahat一、什么是规则引擎定义:规则引擎是一种软件系统,用于执行基于规则的推理。它将业务规则与事实数据相结合,得出结论。组成:规则引擎通常由规则存储库、推理引擎、工作内存 3个部分......
  • C# Console application start wpf window via Application, Encapsulates a Windows
    usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows;usingSystem.Windows.Controls;usingSystem.Windows.Data;usingSystem.Windows.Media.Imaging;namespaceConsoleApp73......
  • 论文笔记--See through Gradients. Image Batch Recovery via GradInversion
    SeethroughGradients.ImageBatchRecoveryviaGradInversion\(W^{FC}\in\mathbb{R}^{M\timesN}\),其输入为一个M维向量\(v\in\mathbb{R}^M\),\(\DeltaW^{FC}_{m,n,k}\)是损失函数对全连接层\(W\)的导数。对于一个特定的类别\(n\),(\(z\)为全连接层输出的logits),其......
  • Graph Edge Partitioning via Neighborhood Heuristic
    目录概符号说明VertexvsEdgepartitioningNE(NeighborExpansion)代码ZhangC.,WeiF.,LiuQ.,TangZ.G.andLiZ.Graphedgepartitioningvianeighborhoodheuristic.KDD,2017.概本文提出了一种图分割方法(edgepartitioning),保证只有少量的重复结点.符号......
  • Jquery中获取iframe的代码(window.top.parent)
    父窗口中操作iframe:window.frames["iframeChild"].document//假如iframe的id为iframeChild在子窗口中操作父窗口:window.parent.document那么,用如果想用jquery的方法,我们怎么用jquery来获取iframe呢?下面是一下收集来的方法。获取页面的对象其实就是dom方法外面加上jq......