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

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.xdnf.cn/news/12618.html

相关文章:

  • python学习打卡day47
  • 6.7本日总结
  • 微前端 - Native Federation使用完整示例
  • Spring Boot 3.3 + MyBatis 基础教程:从入门到实践
  • JAVA理论第五章-JVM
  • Oracle 审计参数:AUDIT_TRAIL 和 AUDIT_SYS_OPERATIONS
  • 仿真每日一练 | Workbench曲柄滑块机构刚体动力学分析
  • 跳转指令四维全解:从【call/jmp 】的时空法则到内存迷宫导航术
  • 数据库系统概论(十七)超详细讲解数据库规范化与五大范式(从函数依赖到多值依赖,再到五大范式,附带例题,表格,知识图谱对比带你一步步掌握)
  • 深入理解PHP安全漏洞:文件包含与SSRF攻击全解析
  • 在线汉字笔画练习工具(HTML文件版)
  • 【LLM-Agent】智能体的记忆缓存设计
  • 《DeepSeek R1-0528与ChatGPT o3对比分析》
  • 在边缘部署实时视觉应用程序
  • AdaFactor Optimizer 大模型训练优化器简介
  • 多线程2(Thread)
  • C++算法-动态规划2
  • 前端基础之《Vue(19)—状态管理》
  • 73 LV的使用(XFS文件系统)
  • CMA软件产品测试报告在哪申请?
  • Dify+Ollama搭建本地知识库
  • C/C++ 中附加包含目录、附加库目录与附加依赖项详解
  • 高精度滚珠导轨在医疗设备中的多元应用场景
  • 江科大读写内部flash到hal库实现
  • STTT(IF:40.8) 清华大学常智杰团队完成雾化外泌体治疗肺纤维化的I期临床试验
  • python学习打卡day46
  • DRV8833 电机控制芯片
  • STM32定时器的种类作用
  • 惠斯通电桥温度补偿优化解决方案
  • 《架构即未来》笔记