欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 美景 > wpf的converter

wpf的converter

2025/6/13 17:04:00 来源:https://blog.csdn.net/lph1972/article/details/148494028  浏览:    关键词: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 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词