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.运行结果

相关推荐
ZC跨境爬虫19 小时前
跟着 MDN 学 HTML day_25:(数字音频概念完全解析)
前端·ui·html·edge浏览器·媒体
LNN202219 小时前
半导体设备 UI 开发工程师:完整工作执行手册
开发语言·python·ui
求学中--20 小时前
状态管理一文通:@State、@Prop、@Link、@Provide/Consume全解析
人工智能·小程序·uni-app·wpf·harmonyos
IT空门:门主1 天前
Pixso UI + Figma + ui-ux-pro-max +ai idae工作流教程
ui·ux·figma·ai idae
qq_452396232 天前
第十八篇:《移动端UI自动化:Appium入门实战》
ui·appium·自动化
罗西的思考2 天前
【GUI-Agent】阿里通义MAI-UI 代码阅读(1)— 总体
人工智能·机器学习·ui·transformer
码途漫谈2 天前
UI-UX-Pro-Max开源项目介绍
人工智能·ui·ai·开源·ai编程·ux
雨浓YN2 天前
GKTGD 工业监控系统-00设计文档
wpf
比特 GOK2 天前
Qt项目ui文件中新添加的控件在代码中不识别的问题解决
开发语言·qt·ui
HAPPY酷2 天前
[UE5 避坑指南] 为什么打包后 UI 消失了?Launch Game 与强制加载
java·ui·ue5