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

相关推荐
Java Fans1 小时前
在WPF项目中集成Python:Python.NET深度实战指南
python·.net·wpf
布伦鸽8 小时前
C# WPF 左右布局实现学习笔记(1)
笔记·学习·c#·wpf
叹一曲当时只道是寻常10 小时前
AI书签管理工具开发全记录(十三):TUI基本框架搭建
ui·go
海尔辛1 天前
Unity UI 性能优化--Sprite 篇
ui·unity·性能优化
QQ676580081 天前
基于 PyTorch 的 VGG16 深度学习人脸识别检测系统的实现+ui界面
人工智能·pytorch·python·深度学习·ui·人脸识别
pop_xiaoli1 天前
UI学习—cell的复用和自定义cell
学习·ui·ios
code bean1 天前
【WPF】WPF 项目实战:构建一个可增删、排序的光源类型管理界面(含源码)
wpf
沉到海底去吧Go2 天前
【图片识别改名】如何批量将图片按图片上文字重命名?自动批量识别图片文字并命名,基于图片文字内容改名,WPF和京东ocr识别的解决方案
ocr·wpf·图片识别改名·图片识别重命名·图片内容改名
lph19722 天前
自定义事件wpf
wpf
code bean2 天前
【WPF】从普通 ItemsControl 到支持筛选的 ItemsControl:深入掌握 CollectionViewSource 用法
wpf