zoukankan      html  css  js  c++  java
  • WPF绑定静态变量的教程(二)

    接上一篇,上面已经完成的数据的绑定,但如果想实现绑定之前对数据进行数据或加条件判断的话,可以使用 IValueConverter

    下面实现一下:

    一、增加一个IValueConverter的实现类

     代码如下,代码的意义是:只显示500以上的数字,500以下的统统显示为0

    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Text;
    using System.Windows.Data;
    
    namespace WpfTestBindStaticField
    {
        public class MyConvert : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (value == null || !(value is int))
                {
                    return 0;
                }
                if ((int)value > 500)
                {
                    return value;
                }
                else
                {
                    return 0;
                }
            }
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    }

    二、修改前台代码

    <Window x:Class="WpfTestBindStaticField.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfTestBindStaticField"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
    
        <Window.Resources>
            <local:StaticList x:Key="statisList"/>
            <local:MyConvert x:Key="myConvert"/>
        </Window.Resources>
        <Grid>
            <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="60" Text="{Binding Source={StaticResource statisList},Path=TestValue,Converter={StaticResource myConvert}}"/>
        </Grid>
    </Window>

    增加了上面标红的代码:Converter={StaticResource myConvert}

    结果如下:

  • 相关阅读:
    Vim常用命令
    [转载] Java注解
    学习Zookeeper之第3章Zookeeper内部原理
    学习Zookeeper之第2章Zookeeper安装
    学习Zookeeper之第1章Zookeeper入门
    《Effective Java 2nd》第8章 通用程序设计
    《Effective Java 2nd》第7章 方法
    Log4j2报错ERROR StatusLogger Unrecognized format specifier
    比较三个数,求最大数字 ( 应用条件运算符:?)
    两个数字比较大小的方法 (分别应用if-else和条件运算符实现)
  • 原文地址:https://www.cnblogs.com/wjx-blog/p/13695908.html
Copyright © 2011-2022 走看看