WPF中数据绑定转换器Converter

使用场景:ViewModel中的数据如果跟View中的数据类型不匹配。

下面是以int类型调控是否可见为例子

步骤一:创建转换器类

在xaml中查看Converter的定义可以知道Converter是一个接口类型,因此转换器的类定义需要使用这个接口

cs 复制代码
internal class VisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if ((int)value == 1)
        {
            return Visibility.Visible;
        } else
        {
            return Visibility.Collapsed;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

-- 方法中value就是xaml中的传入值

xaml中的使用该转换器:

首先将该资源引用

XML 复制代码
<Window.Resources>
    <local:VisibilityConverter x:Key="vc"/>
</Window.Resources>

然后通过静态资源按照key直接使用就行了

XML 复制代码
Visibility="{Binding MyProperty, Converter={StaticResource vc}}

附加

如果需要使用Bool类型去控制是否显示,wpf有帮我们写好了BooleanToVisibilityConverter,直接在资源中引用,指定好Key就可以直接使用了

相关推荐
weixin1997010801615 小时前
《大促护航:电商API限流与降级,双11峰值500万调用的架构复盘》(附Python源码)
python·架构·wpf
hh9501 天前
gent Plan x DeepSeek Harness:多 Agent 协作场景下的中央编排实践
人工智能·wpf·adg·火山引擎·agent plan·adg成都社区
Vae_Mars1 天前
WPF中的Lazy<T>使用方法
wpf
zQ.ii2 天前
WPF 触发器学习笔记
笔记·学习·wpf
SamChan902 天前
用PostgreSQL+pgvector构建PDF翻译记忆库:向量相似度检索+增量更新实战
数据库·python·ai·postgresql·pdf·wpf
李高钢3 天前
开源控件库 HandyControl 介绍与简单实践:让 WPF 界面告别“上个世纪“
开源·wpf
旋生万物3 天前
【终极实战】用Python从零“生成“一个宇宙:螺旋干涉模型的代码实现
开发语言·前端·人工智能·react.js·php·wpf
Now喔3 天前
WPF画刷介绍
wpf
李高钢4 天前
WPF/WinForms 客户端通过 gRPC 与后端通信:从 Proto 契约到流式调用的完整指南
wpf·grpc·winforms
一见已难忘5 天前
基于 Harmony 6.0 应用的宠物寄养预约系统实现
wpf·宠物