WPF 值转换器


1、举例

<Window x:Class="WpfApplication1.com.view.TestWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1.com.Data"
        Title="测试窗口" Height="300" Width="500">
    <Window.Resources>
        <local:StringToStringConvert x:Key="stringToStringConvert"/>
    </Window.Resources>
    <Grid>
        
        <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Orientation="Horizontal">
            <Label Content="姓名:"/>
            <Label Content="{Binding StudentName,Converter={StaticResource stringToStringConvert}}"/>
        </StackPanel>
        
    </Grid>
</Window>

using System.Windows;
using WpfApplication1.com.Data;

namespace WpfApplication1.com.view
{
    /// <summary>
    /// TestWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TestWindow : Window
    {
        public TestWindow()
        {
            InitializeComponent();

            StudentData stuData = new StudentData();
            stuData.StudentID = 100;
            stuData.StudentName = "小明";

            this.DataContext = stuData;
        }
    }
}
using System;
using System.Globalization;
using System.Windows.Data;

namespace WpfApplication1.com.Data
{
    [ValueConversion(typeof(string),typeof(string))]
    public class StringToStringConvert : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string str = System.Convert.ToString(value);
            if (str != "")
                return "你好";
            return "";
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();//不用的话可以不做处理
        }
    }
}


此代码中的StudentData数据类是实现了INotifyPropertyChanged接口的数据类,

值转换器需要实现IValueConverter接口

Convert函数:将某个值转换为目标类型

ConvertBack方法与其相反

ValueConversion特性不是必需的,但是易读容易理解,有两个参数,第一个是源类型,第二个是目标类型



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值