C# WPF在页面中如何数据转换

一、项目中创建一个转换的类

我们已知的一个字段是一个bool类型,需要转换为一个string类型。
例如 :
true 需要转换为 已备份
false 需要转换为 云备份
或者对bool类型进行取反
true 需要转换为 false
false 需要转换为 true

创建一个转换的类,继承IValueConverter接口

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace UserControlTest
{
    public class ButtonContentConvert : IValueConverter
    {
    	//bool 转化为 string
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if ((bool)value)
            {
                return "已备份";
            }
            return "云备份";
        }
		//不会调用,为了实现接口
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    // bool 取反
    public class ButtonIsEnableConvert : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return !(bool)value;
        }
		//不会调用,为了实现接口
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

二、在界面中引用

在界面中的添加资源属性
其中 bccbiec 为第一步写的方法。
PS:bvc 同理,本人这里是把bool转换成Visibility需要的属性。
在这里插入图片描述
PS:可能会报错,重新生成一下即可

<Window.Resources>
    <local:ButtonContentConvert x:Key="bcc"/>
    <local:ButtonIsEnableConvert x:Key="biec"/>
</Window.Resources>

然后在需要转换的地方添加Convert属性
在这里插入图片描述
参考代码:

<Button  Content="{Binding IsUpdate,Converter={StaticResource bcc}}" IsEnabled="{Binding IsUpdate,Converter={StaticResource biec}}" />
<Button Content="下载" Margin="10,0" Visibility="{Binding IsUpdate,Converter={StaticResource bvc}}" />
<Button Content="删除" Visibility="{Binding IsUpdate,Converter={StaticResource bvc}}" />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值