C# WPF 转换器使用(IValueConverter)

使用场景:比如性别数据库存储是0和1,页面上要显示男女,此时就需要用到转换器。

转换器使用三步骤:

1. 定义转换器(class类)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace IngoDesignPDMS
{
    public class ConverIsPublishIsEnabled : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            // 这里进行转换
            return !(bool)value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //这里跟上面相反,转回去。
            throw new NotImplementedException();
        }
    }
}

2.引用转换器(xaml页面),注意放在Page.Resources节点下。

<Page x:Class="IngoDesignPDMS.DatabasePublishing"
    <Page.Resources>
        <local:ConverIsPublishIsEnabled x:Key="ConverIsPublishIsEnabled" />
    </Page.Resources>
</Page>

3.使用转换器,只截取了重要代码段,我这是转成bool值给IsEnabled使用,也可以给Content属性用,语法都是一样的。

<Button Click="BtnEdit_Click"  Name="btnEdit" Height="24" Style="{StaticResource ButtonColor}" Width="60" Content="编辑内容" Margin="10,0,0,0" IsEnabled="{Binding IsPublish,Converter={StaticResource ConverIsPublishIsEnabled}}"/>

猜你喜欢

转载自blog.csdn.net/weixin_42193688/article/details/118967536