wpf 数据绑定 数据转换

1.概要

数据绑定,有时候绑定的数据源和目标的数据类型不同,这时候就需要转换。

2.代码

2.1 xaml(eXtensible Application Markup Language) 可扩展应用程序标记语言

复制代码
<Window x:Class="WpfApp6.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:WpfApp6"
        mc:Ignorable="d"
        Title="MainWindow" Height="100" Width="300">
    <Window.Resources>
        <local:boolchange x:Key="boolkey"></local:boolchange>
    </Window.Resources>
    <StackPanel>
        <TextBox Name="source1"></TextBox>
        <TextBlock Text="YES"></TextBlock><CheckBox IsChecked="{Binding ElementName=source1, Path=Text,Converter={StaticResource boolkey}}"></CheckBox>
    </StackPanel>
</Window>

2.2 code

复制代码
using System.Globalization;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp6
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
    public class boolchange : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string? str = value.ToString().ToLower();
            switch(str)
            {
                case "yes":
                    return true;
                case "no": 
                    return false;    
            }
            return false;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

3.运行结果

相关推荐
Emma_Maria1 天前
关于vant-ui-vue 的datepicker 时间选择错乱问题的处理
前端·vue.js·ui
BW.SU1 天前
RUI Builder-图形化UI设计-工程范例
stm32·单片机·嵌入式硬件·ui·界面设计·单片机驱动彩屏·ra8889
加油=^_^=2 天前
【C++11】特殊类设计 | 类型转换
c++·单例模式·类型转换
Devlab2 天前
anyui - Master designer for LVGL [New release v0.40.0]
嵌入式硬件·物联网·低代码·ui·iot
小新1102 天前
vs2022+Qt插件初体验,创建带 UI 界面的 Qt 项目
开发语言·qt·ui
北极糊的狐2 天前
三星 One UI 8 停止支持 三星Dex后的替代指南
ui
狮智先生2 天前
【编程实践】Windows + PySide6 + Matplotlib 绘图时 WinError 32 的完整排查与解决方案
windows·ui·个人开发·matplotlib·交通物流
starrycode8882 天前
【每日一个知识点】Kotlin开发基础知识
ui·kotlin
没有bug.的程序员3 天前
SOA、微服务、分布式系统的区别与联系
java·jvm·微服务·架构·wpf·日志·gc
企微自动化3 天前
企业微信客户端 UI 自动化定位技术的稳定性和局限性
ui·自动化·企业微信