zoukankan      html  css  js  c++  java
  • Silverlight Converter的使用

    在系统设计中,常会遇到代码字典转换的问题,比如员工代码转名字,状态转颜色等,这时候就可以使用Converter

    首先在项目创建一个类,继承并实现IValueConverter接口。实现方法后,在前台直接使用。

    为了演示效果,我这里模拟了一个餐饮点餐界面座位状态颜色转换(预定,消费中,结账中,转换成对应的颜色)

    IValueConverter代码如下

    public class DeskStateConvert : IValueConverter
        {
    
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                System.Windows.Media.Color C = System.Windows.Media.Color.FromArgb(255, 83, 59, 31);
                if (value != null)
                {
                    int i = (int)value;
                    //预定
                    if (i == 1)
                    {
                        C = System.Windows.Media.Colors.Green;
                    }
                    //消费中
                    else if (i == 2)
                    {
                        C = System.Windows.Media.Colors.Red;
                    }
                    //结账中
                    else if (i == 3)
                    {
                        C = System.Windows.Media.Colors.Blue;
                    }
                }
                return new System.Windows.Media.SolidColorBrush(C);
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                return null;
            }
        }

    前台使用方式如下

     xmlns:uc="clr-namespace:SilverUITest"   //添加转换类的名称空间

    //添加资源映射
    <UserControl.Resources> <uc:DeskStateConvert x:Key="DeskStateConvert" /> </UserControl.Resources>

     <Button Width="100" Height="80" Content="{Binding Name}" Background="{Binding State,Converter={StaticResource DeskStateConvert}}" />

    也有另外一种简单的方法, 如果是系统里有大量的转换处理,可以使用另外一个转换方法,使用本地资源字典

    1:添加一个sliverlight资源文件

    2:添加转换类的名称空间

    3:添加转换类映射

    资源文件代码如下

    <ResourceDictionary
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:uc="clr-namespace:SilverUITest">
        <uc:DeskStateConvert x:Key="DeskStateConvert" />
    </ResourceDictionary>

    然后再程序的App.xaml中添加资源文件的映射,如果你不想整个项目使用,那就在对应的每个界面添加整个资源文件映射,

    我这里演示第一种,代码如下

    <Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                 x:Class="SilverUITest.App"
                 >
        <Application.Resources>
            <ResourceDictionary Source="Dictionary1.xaml"/>
        </Application.Resources>
    </Application>

    然后具体界面使用方法跟第二段代码一样。

    效果如下

  • 相关阅读:
    求矩形最大面积
    异或相关知识
    算法模板-线段树区间最值
    矩阵递推关系的建立 and 矩阵快速幂
    二分答案模板
    关于STL,set,vector,map的时间
    域名解析
    CDN配置
    CDN的工作原理及好处
    打赏
  • 原文地址:https://www.cnblogs.com/Rmeo/p/3023828.html
Copyright © 2011-2022 走看看