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

相关推荐
低调小一1 天前
Google A2UI 入门:让 Agent “说 UI”,用声明式 JSON 安全渲染到原生界面
人工智能·安全·ui·json
gAlAxy...1 天前
MyBatis 缓存深度解析(一级 / 二级缓存原理 + 实战 + 避坑)
wpf
Swift社区1 天前
Flutter / RN / iOS 的 UI 渲染机制,本质差异在哪里?
flutter·ui·ios
伶俐的猪1 天前
UI_Testing 项目详细文档
开发语言·javascript·ui
潜龙95271 天前
基于大模型(LLM)的 Web UI 自动化方案
前端·ui·自动化
小陈phd1 天前
大语言模型实战(十一)——基于MAI-UI-8B 实现 Android UI 自动化:从元素定位到多步导航
android·ui·自动化
泉飒1 天前
WinForm与WPF的异同点
wpf·winform
我送炭你添花1 天前
Pelco KBD300A 模拟器:第7篇. 宏脚本编辑器设计与解释器实现
python·ui·自动化·编辑器·运维开发
fireworkseasycold2 天前
wpf 基于 JSON 的扩展配置 (Extended Config)” 功能
oracle·json·wpf
脩衜者2 天前
极其灵活且敏捷的WPF组态控件ConPipe 2026
前端·物联网·ui·wpf