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}

结果如下:

posted @   星星c#  阅读(1115)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2016-09-19 3des用法示例,已测试
2016-09-19 制作Windows服务项目详细攻略
2016-09-19 利用好压在C#程序里实现RAR格式的压缩和解压功能
2016-09-19 winform里textBox无法获得焦点的解决方案
点击右上角即可分享
微信分享提示