一、项目中创建一个转换的类
我们已知的一个字段是一个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();
}
}
二、在界面中引用
在界面中的添加资源属性
其中 bcc 与 biec 为第一步写的方法。
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}}" />