自定义值转换器

当我们在前台写页面的时候,有时候后台给我们的数据并不是现成可用的,我们需要自己再转化一下才可以使用,所以,我们需要创建一个前台的数据转化工具类

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

namespace GridExp
{
    public class BoolVisibilityConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, string language)
        {
            //value是Model中的数据,返回值是转换后UI中的数据
            bool b = (bool)value;
            return b ? Visibility.Visible : Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            //value是UI中的数据类型转换成为Model中的值(TwoWay绑定)
            Visibility v = (Visibility)value;
            return v == Visibility.Visible;
        }
    }
}

再在第一个标签里面引用这个类所在的命名空间

<common:LayoutAwarePage
    x:Name="pageRoot"
    x:Class="GridExp.GroupedItemsPage"
    DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:GridExp"
    xmlns:data="using:GridExp.Data"
    xmlns:common="using:GridExp.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">


再设定一个资源,相当于在这个页面里面NEW了一个对象

  <Page.Resources>

        <!--
            此页所显示的分组项的集合,绑定到完整
            项列表的子集,因为无法虚拟化组中的项
        -->
        <local:BoolVisibilityConverter x:Key="booVisConverter"></local:BoolVisibilityConverter>


最后,在调用的地方使用

   <Image Source="images/w_mengchong.jpg" Visibility="{Binding IsUnMem,Converter={StaticResource booVisConverter}}" Width="50" Height="50"></Image>
原文地址:https://www.cnblogs.com/zhuzhenyu/p/2799918.html