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就可以直接使用了

相关推荐
光泽雨2 天前
动画生命周期
c#·wpf
nap1173 天前
WPF 中常用的 LINQ 语句
wpf
做个文艺程序员6 天前
MQ第12篇:AI原生消息架构演进:从MQ到事件驱动的全链路设计
架构·消息队列·wpf·事件驱动架构·ai-native·cqrs
donk13148 天前
React Native for OpenHarmony 实战:三方库 react-native-circular-action-menu 的鸿蒙化适配指南
javascript·分布式·react native·react.js·wpf·harmonyos
donk13149 天前
React Native for OpenHarmony 实战:三方库 react-native-step-indicator 的鸿蒙化适配指南
分布式·react native·react.js·wpf·harmonyos
He BianGu9 天前
【笔记】WPF中RenderOptions类的详细功能
笔记·wpf
VidDown9 天前
上线三个月后的第一次事故:一个 Django 服务的日志、监控与故障复盘
数据库·python·django·wpf·音视频·视频编解码
He BianGu9 天前
【笔记】WPF中CachingHint的功能
笔记·wpf
He BianGu9 天前
【笔记】在WPF中BitmapScalingMode的作用
笔记·wpf