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

相关推荐
c#上位机12 小时前
wpf之MVVM中只读属性更新界面
c#·wpf·mvvm
就是有点傻12 小时前
WPF自定义控件之环形进度条
wpf
He BianGu12 小时前
【笔记】WPF中如何的动态设置DataGridTextColumn是否显示
笔记·wpf
Pota-to成长日记15 小时前
Redisson 看门狗机制深度解析:分布式锁的守护者
分布式·wpf
为java加瓦16 小时前
分布式单例模式在微服务架构中的关键作用与实践
wpf
c#上位机17 小时前
wpf之Ellipse控件
wpf
c#上位机17 小时前
wpf之GroupBox
c#·wpf
分布式存储与RustFS1 天前
告别手动配置:用 Terraform 定义你的 RustFS 存储帝国
云原生·wpf·文件系统·terraform·对象存储·minio·rustfs
c#上位机2 天前
wpf之TabControl
c#·wpf
mingupup2 天前
WPF应用最小化到系统托盘
wpf