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

相关推荐
qq_4523962316 小时前
第九篇:《处理常见复杂UI组件:下拉框、弹窗、iframe、多窗口》
ui
深蓝海拓17 小时前
Qt:创建一套基于HSL颜色体系的颜色库
笔记·python·qt·学习·ui
for_ever_love__17 小时前
UI学习:反向传值(代理传值)深入学习
学习·ui·objective-c
Cho1yon18 小时前
【AI Agent 第十期:基于 scrcpy + PyTorch 的车载系统多屏自动化测试工具开发】
人工智能·pytorch·ui·车载系统·自动化
我家媳妇儿萌哒哒18 小时前
Element ui el-dialog 在一个有滚动条的页面,打开一个弹框,完了再打开一个弹框后,滚动条可以滚动,怎么限制不能滚动。
前端·vue.js·ui
ZC跨境爬虫18 小时前
Apple官网复刻第二阶段day_3:(还原苹果官网iPhone顶部标准文案区块,一次编写全局复用)
前端·css·ui·html·iphone
ZC跨境爬虫19 小时前
Apple官网复刻第二阶段day_2:(前端模块化还原苹果官网WATCH海报)
前端·ui·重构·html·状态模式
Wild API19 小时前
GPT Image 2测评总结:文本渲染、UI生成、角色一致性与提示词模板
gpt·ui
武藤一雄19 小时前
WPF中逻辑树(Logical Tree)与可视化树(Visual Tree)到底是什么
microsoft·c#·.net·wpf·.netcore
炸炸鱼.20 小时前
ELK 企业级日志分析系统完整部署手册
elk·wpf