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

相关推荐
I'mSQL15 小时前
WPF资源字典合并报错
wpf
one99620 小时前
WPF应用程序中的异常处理
c#·.net·wpf
somethingGoWay2 天前
wpf .netcore 导出docx文件
wpf·.netcore
somethingGoWay2 天前
wpf .netcore 导出pdf文件
pdf·wpf·.netcore
self_myth3 天前
[特殊字符] 深入理解操作系统核心特性:从并发到分布式,从单核到多核的全面解析
windows·macos·wpf·harmonyos
c#上位机3 天前
wpf之TextBlock
c#·wpf
玉面小君4 天前
从 WPF 到 Avalonia 的迁移系列实战篇6:ControlTheme 和 Style区别
c#·wpf·avalonia
c#上位机5 天前
wpf之Border
c#·wpf
SunflowerCoder5 天前
WPF迁移avalonia之图像处理(一)
图像处理·wpf·avalonia
周杰伦fans5 天前
WPF中的DataContext以及常见的绑定方式
wpf