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#上位机1 天前
wpf之ControlTemplate
wpf
kyranhan3 天前
WPF,窗口拖动事件与窗口内控件点击事件
wpf
孟婆来包棒棒糖~4 天前
SpringCloude快速入门
分布式·后端·spring cloud·微服务·wpf
Humbunklung4 天前
C# WPF 实现读取文件夹中的PDF并显示其页数
pdf·c#·wpf·npoi·gemini·itext
wangnaisheng4 天前
【WPF】NumericUpDown的用法
wpf
步、步、为营4 天前
.NET 9 RC1 正式发布
.net·wpf
界面开发小八哥6 天前
界面组件DevExpress WPF中文教程:Grid - 如何过滤节点?
.net·wpf·界面控件·devexpress·ui开发
I'mSQL6 天前
C#与WPF使用mvvm简单案例点击按钮触发弹窗
开发语言·c#·wpf
百锦再7 天前
WPF依赖属性深度解析:从原理到高级应用
wpf·依赖·绑定·验证·net·强制
✎ ﹏梦醒͜ღ҉繁华落℘7 天前
WPF高级学习(一)
学习·wpf