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

相关推荐
TracyCoder12312 小时前
RocketMQ技术原理简单解析:从架构到核心流程
架构·wpf·rocketmq
烽火聊员14 小时前
SSLSocket 服务器端WPF C#测试代码
开发语言·c#·wpf·ssl
暮雪倾风14 小时前
【WPF开发】加载solidworks的3D模型
wpf
Macbethad15 小时前
高性能 CANopen 主站程序技术方案 (基于 WPF)
网络协议·wpf·信息与通信
Macbethad1 天前
使用WPF编写一个工控软件设置界面
wpf
wuli_滔滔1 天前
【探索实战】深入浅出:使用Kurator Fleet实现跨云集群的统一应用分发
架构·wpf·kurator·fleet
松☆1 天前
Flutter 与 OpenHarmony 深度集成:自定义 MethodChannel 插件开发全指南
flutter·wpf
Aevget2 天前
界面控件DevExpress WPF中文教程:Data Grid - 虚拟源限制
hadoop·wpf·界面控件·devexpress·ui开发
听风吟丶2 天前
Java 微服务日志实战:ELK+SkyWalking 构建全链路日志监控与智能告警体系某电商平台曾因日志问题陷入
wpf
她说彩礼65万2 天前
WPF 样式
大数据·hadoop·wpf