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

相关推荐
明耀1 小时前
WPF DataGrid 默认显示行号
wpf
fyifei05585 小时前
WPF学习PropertyChanged
wpf
爱炸薯条的小朋友5 小时前
C#由于获取WPF窗口名称造成的异常报错问题
windows·c#·wpf
baivfhpwxf20236 小时前
wpf ListBox 去除item 单击样式
wpf
诗仙&李白6 小时前
lnnovationHubTool,用prism+WPF编写的MVVM模式的快速上位机软件开发框架平台
wpf·mvvm·prism·上位机软件开发框架平台
程序员小刘9 小时前
【HarmonyOS 5】教育开发实践详解以及详细代码案例
华为·wpf·harmonyos
Java Fans1 天前
在WPF项目中集成Python:Python.NET深度实战指南
python·.net·wpf
布伦鸽1 天前
C# WPF 左右布局实现学习笔记(1)
笔记·学习·c#·wpf
code bean2 天前
【WPF】WPF 项目实战:构建一个可增删、排序的光源类型管理界面(含源码)
wpf