• WPF学习整理总结 --转换器


    作用

    1.可以将源数据和目标数据之间进行特定的转化

    2.定义转换器,需要继承接口IValueConverter

     class ForeColorConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (value == null) throw new ArgumentNullException("value can not be null");
                int index = System.Convert.ToInt32(value);
                if (index == 0)
                    return "Blue";
                else if (index == 1)
                    return "Red";
                else
                    return "Green";
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                return null;
            }
        }

    Convert:会进行源属性传给目标属性的特定转化

    ConvertBack:会进行目标属性传给源属性的特定转化

    参数parameter:对应Binding的ConverterParameter属性

    3.使用转换器

    (1)引用转换器所在的命名空间

      xmlns:local="clr-namespace:Converter"

    (2)定义资源

     <UserControl.Resources>
            <local:ForeColorConverter x:Key="forColorConverter"/>
        </UserControl.Resources>

    (3)定义属性

      public UserControl1()
            {
                InitializeComponent();
                this.DataContext = new ViewModel();
            }
            public class ViewModel : ViewModelBase
            {
                private int status = 0;
                public int Status
                {
                    get => status; set { status = value; RaisePropertyChanged(" Status"); }
    
                }
            }

    (4)绑定属性,添加转换器

    <Grid>
            <Label HorizontalAlignment="Left" Height="23" Margin="243,208,0,0" Content="这里哦" Foreground="{Binding Status,Converter={StaticResource forColorConverter},Mode=OneWay}" VerticalAlignment="Top" Width="120"/>
            <TextBox x:Name="tbName" HorizontalAlignment="Left" Height="23" Margin="243,160,0,0" TextWrapping="Wrap" Text="{Binding Status,UpdateSourceTrigger=LostFocus,Mode=OneWayToSource}" VerticalAlignment="Top" Width="120"/>
            <Button Content="Button" HorizontalAlignment="Left" Margin="389,160,0,0" VerticalAlignment="Top" Width="75"/>
        </Grid>
     
  • 相关阅读:
    洛谷P1306 斐波那契公约数
    Codevs 1688 求逆序对(权值线段树)
    poj1006 Biorhythms
    2017-9-2 NOIP模拟赛
    洛谷P1633 二进制
    洛谷P2513 [HAOI2009]逆序对数列
    洛谷P2687 [USACO4.3]逢低吸纳Buy Low, Buy Lower
    洛谷P2285 [HNOI2004]打鼹鼠
    2017-8-31 NOIP模拟赛
    洛谷P2134 百日旅行
  • 原文地址:https://www.cnblogs.com/jiangxiaoming/p/14236428.html
Copyright © 2020-2023  润新知