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

相关推荐
精神底层4 小时前
拒绝 UI 卡死!我用 CSnakes 实时拦截 Python 训练流,在 WPF 中重构了 ScottPlot 5 高性能 AI 看板
python·ui·wpf
贪玩的小松鼠1 天前
WPF基础到企业应用系列7——深入剖析依赖属性(WPF/Silverlight核
wpf
界面开发小八哥1 天前
界面控件DevExpress WPF v26.1新版亮点 - TreeView、Spreadsheet控件功能升级
.net·wpf·界面控件·devexpress·ui开发
斯文的八宝粥2 天前
WPF企业内训全程实录(下)
大数据·hadoop·wpf
精明的身影4 天前
深入WPF -- Dispatcher(补)
wpf
云中飞鸿5 天前
该如何进行WPF界面设计
wpf
云中飞鸿6 天前
WPF分哪几块
wpf
newbe365246 天前
我们如何使用 impeccable 优化前端界面设计与实现稳定性
前端·人工智能·分布式·github·aigc·wpf
Chris _data24 天前
WPF 学习第三天 — Modbus RTU 串口通信
hadoop·学习·wpf
布吉岛的石头25 天前
Java 程序员第 43 阶段05:微服务整合大模型,跨服务调用架构设计实战,Seata分布式事务实战
wpf