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

相关推荐
青稞社区.7 分钟前
小米大模型 Plus 团队提出BTL-UI:基于直觉-思考-关联的GUI Agent推理
人工智能·ui
weixin_5316518142 分钟前
@clack/prompts 命令行终端中构建交互式用户界面
ui
Larry_Yanan1 小时前
Qt多进程(四)QTcpSocket
开发语言·c++·qt·ui
wtrees_松阳5 小时前
【弦断处见真章】:鸿蒙UI三重境之《UIContext》心法探幽
ui·华为·harmonyos
IT古董6 小时前
企业级官网全栈(React·Next.js·Tailwind·Axios·Headless UI·RHF·i18n)实战教程-第四篇:登录与注册系统(核心篇)
javascript·react.js·ui
梦想的旅途26 小时前
基于 UI 驱动(RPA)实现企业微信外部群自动化推送的技术逻辑
ui·自动化·企业微信·rpa
要记得喝水7 小时前
某公司WPF面试题(含答案和解析)--3
wpf
JosieBook7 小时前
【UI设计】智慧政务大屏 UI 设计深度解析:从战略意图到像素级落地
ui·政务
xinyu_Jina1 天前
Info Flow:大规模列表渲染中的UI虚拟化、数据懒-加载与前端性能工程
前端·ui
zzyzxb1 天前
WPF中Adorner和Style异同
wpf