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

相关推荐
baivfhpwxf20239 小时前
WPF DataGrid 指定列的数据可以编辑功能开发
wpf
求学中--1 天前
万物互联的钥匙:HarmonyOS SDK 深度解析与实战指南
wpf
武藤一雄1 天前
WPF Command 设计思想与实现剖析
windows·微软·c#·.net·wpf·.netcore
Aevget1 天前
DevExpress WPF中文教程:Data Grid - 服务器模式和即时反馈模式
.net·wpf·界面控件·devexpress·ui开发
武藤一雄1 天前
WPF 资源解析:StaticResource & DynamicResource 实战指南
微软·c#·.net·wpf·.netcore
c#上位机1 天前
wpf路径
wpf
武藤一雄1 天前
WPF UI 开发深度指南:资源 (Resources)、样式 (Style) 与触发器 (Trigger) 全解析
ui·c#·.net·wpf·.netcore·avalonia
Poetinthedusk2 天前
WPF获得当前电脑的储存和运存
wpf
unicrom_深圳市由你创科技2 天前
Qt、MFC、WinForm、WPF,哪个做上位机界面更好?
qt·wpf·mfc
暮雪倾风3 天前
【WPF】使用Costura.Fody将工程打包为单个EXE文件
wpf·exe·windows原生开发