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}

結果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM