wpf的converter

发布于:2025-06-08 ⋅ 阅读:(19) ⋅ 点赞:(0)

单例模式


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 


网站公告

今日签到

点亮在社区的每一天
去签到