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 小时前
鸿蒙跨端框架Flutter学习day 2、常用UI组件-层叠布局 Stack & Positioned
学习·flutter·ui·实时互动·harmonyos·鸿蒙
航Hang*8 小时前
Photoshop 图形与图像处理技术——第9章:实践训练1——绘制禁烟标志和奥运五环
图像处理·笔记·学习·ui·photoshop
未定义.22111 小时前
第5篇:进阶优化:数据驱动+日志体系+失败重试实战
python·ui·自动化·jenkins·集成测试·pytest
上海物联网12 小时前
Prism Regions-自定义区域适配器实现开发者将任意 WPF 控件转换为可动态加载视图的区域容器
面试·wpf
世人万千丶13 小时前
鸿蒙跨端框架Flutter学习day 2、常用UI组件-折行布局 Wrap & Chip
学习·flutter·ui·华为·harmonyos·鸿蒙
未定义.22114 小时前
第4篇:企业级框架搭建,Pytest+PO模式从0到1实战
python·ui·自动化·jenkins·集成测试·pytest
尤老师FPGA1 天前
使用ZYNQ芯片和LVGL框架实现用户高刷新UI设计系列教程(第四十四讲)
ui
小雨下雨的雨1 天前
Flutter 框架跨平台鸿蒙开发 —— SingleChildScrollView 控件之长内容滚动艺术
flutter·ui·华为·harmonyos·鸿蒙
zFox1 天前
五、开始项目实战(搭建完整项目)
ui·kotlin
guangzan1 天前
AI → JSON → UI
ui·ai·zod