当前位置: 首页 > news >正文

wpf的converter

单例模式


using System;

using System.Globalization;

using System.Windows.Data;

 

namespace YourNamespace

{

    public class HalfWidthConverter : IValueConverter

    {

        // 静态实例

        public static readonly HalfWidthConverter Instance = new HalfWidthConverter();

 

        // 私有构造函数,防止外部直接实例化

        private HalfWidthConverter()

        {

        }

 

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)

        {

            if (value is double width)

            {

                return width / 2.0;

            }

            return 0.0; // 如果输入值不是double类型,返回0

        }

 

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

        {

            if (value is double halfWidth)

            {

                return halfWidth * 2.0; // 将一半的宽度转换回原始宽度

            }

            return 0.0; // 如果输入值不是double类型,返回0

        }

    }

}

单例模式不用资源


<Window x:Class="YourNamespace.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:local="clr-namespace:YourNamespace"

        Title="MainWindow" Height="350" Width="525">

    <Grid x:Name="parentGrid">

        <TextBox Width="{Binding ActualWidth, ElementName=parentGrid, Converter={x:Static local:HalfWidthConverter.Instance}}" />

    </Grid>

</Window>

不用单例则


 <TextBox Width="{Binding ElementName=parentGrid, Path=ActualWidth, Converter={StaticResource HalfWidthConverter}}" />    

是staticresource 

 

资源存放位置

binding 属性,elementname/source/relativesource ,converter 

 

source x static 

relativesource=relativesoure   self/findancestor ancestortype 

http://www.lqws.cn/news/198937.html

相关文章:

  • 【Java微服务组件】分布式协调P4-一文打通Redisson:从API实战到分布式锁核心源码剖析
  • Puppeteer API
  • 每日Prompt:治愈动漫插画
  • ubuntu20使用自主探索算法explore_lite实现机器人自主探索导航建图
  • Keil开发STM32生成hex文件/bin文件
  • 数据结构之栈
  • 《绩效管理》要点总结与分享
  • 大数据(2) 大数据处理架构Hadoop
  • Linux(13)——Ext系列文件系统
  • jenkins gerrit-trigger插件配置
  • Python Copilot【代码辅助工具】 简介
  • 数据库系统概论(十七)超详细讲解数据库规范化与五大范式(从函数依赖到多值依赖,再到五大范式,附带例题,表格,知识图谱对比带你一步步掌握)
  • Docker容器部署elasticsearch8.*与Kibana8.*版本使用filebeat采集日志
  • SAP学习笔记 - 开发26 - 前端Fiori开发 OData V2 和 V4 的差异 (Deepseek整理)
  • 阿里云MaxCompute入门
  • Fetch与Axios:区别、联系、优缺点及使用差异
  • 使用Python和Scikit-Learn实现机器学习模型调优
  • LinkedList、Vector、Set
  • ⚡️ Linux Docker 基本命令参数详解
  • 开源之夏·西安电子科技大学站精彩回顾:OpenTiny开源技术下沉校园,点燃高校开发者技术热情
  • C++2025.6.7 C++五级考题
  • 在Ubuntu上使用 dd 工具制作U盘启动盘
  • 【hadoop】相关集群开启命令
  • STM32的系统滴答定时器简述
  • 在 Win10 上 WSL 安装 Debian 12 后,Linux 如何启动 SMTP 服务?
  • 人工智能--AI换脸
  • 【工作记录】接口功能测试总结
  • 基于vscode,idea,java,html,css,vue,echart,maven,springboot,mysql数据库,在线考试系统
  • LeetCode刷题 -- 542. 【01 矩阵】最短距离更新算法实现(双向DP)
  • Vue学习之---nextTick