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

相关推荐
beyond谚语5 小时前
第三章 布局
wpf
Aevget18 小时前
界面控件DevExpress WPF v25.1新版亮点:数据管理功能全新升级
.net·wpf·界面控件·devexpress·ui开发
baivfhpwxf202318 小时前
要在 WPF 中实现数据表对应实体的属性与 UI 控件的双向绑定,并支持修改通知和 UI 自动更新
c#·wpf
极客智造1 天前
深入解析 WPF 中的 DataTemplateSelector:动态模板选择的艺术
wpf
极客智造1 天前
WPF 高级 UI 定制:深入解析 VisualStateManager 与 Adorner
wpf
LateFrames3 天前
使用 Winform / WPF / WinUI3 / Electron 实现异型透明窗口
javascript·electron·wpf·winform·winui3
ifeng09183 天前
HarmonyOS实战项目:AI健康助手(影像识别与健康分析)
人工智能·华为·wpf·harmonyos
Aevget3 天前
界面控件Telerik UI for WPF 2025 Q3亮点 - 集成AI编码助手
人工智能·ui·wpf·界面控件·ui开发·telerik
张人玉3 天前
WPF 数据绑定与转换器详解
c#·wpf·light
主宰者3 天前
WPF CalcBinding简化判断逻辑
c#·.net·wpf