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

相关推荐
xcLeigh6 小时前
WPF进阶 | WPF 数据绑定进阶:绑定模式、转换器与验证
c#·wpf
黑金IT8 小时前
Python3 + Qt5:实现AJAX异步更新UI
qt·ui·ajax
喵叔哟13 小时前
5. 【Vue实战--孢子记账--Web 版开发】-- 主页UI
前端·vue.js·ui
山海青风1 天前
Axure入门教程 -- 第五章:原型优化与调试
ui·交互·axure
学与用2 天前
【deepseek实战】绿色好用,不断网
ai·c#·wpf
浅陌sss3 天前
Unity 粒子特效在UI中使用裁剪效果
ui·unity·游戏引擎
机器视觉小小测试员3 天前
工业相机常用词语解释
运维·ui·自动化·工业相机
的不对不3 天前
WPF基础03——InitializeComponent()函数解释
windows·c#·.net·wpf
PersistJiao4 天前
Couchbase UI: Search
ui·couchbase
军训猫猫头4 天前
61.异步编程1 C#例子 WPF例子
开发语言·c#·wpf