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

相关推荐
500846 分钟前
Conv + BN + ReLU 融合:省掉两次显存读写
flutter·架构·开源·wpf·音视频
5008413 分钟前
把 FlashAttention 讲清楚
flutter·electron·wpf
CSharp精选营2 小时前
.NET 8 Web开发入门(六):Blazor 全栈开发——告别 JavaScript 焦虑
数据绑定·signalr·组件化开发·全栈开发·blazor server·blazor web·c# 写前端
500846 小时前
ATC 做了什么:从 ONNX 到 .om
分布式·架构·开源·wpf·开源鸿蒙
500848 小时前
Graph Engine 是什么,为什么需要它
java·人工智能·性能优化·ocr·wpf
范同学~9 小时前
多个表单如何用element ui 校验
javascript·vue.js·ui
JohnnyDeng949 小时前
Paging 3 分页加载架构全解析:从数据源到 UI 的完整链路
android·ui·kotlin
ZC跨境爬虫10 小时前
跟着 MDN 学CSS day_8:(盒模型完全解)
前端·javascript·css·ui·交互
ZC跨境爬虫10 小时前
跟着 MDN 学CSS day_6:(伪类和伪元素详解)
前端·javascript·css·数据库·ui·html
x***r15110 小时前
AxureRP-Setup安装步骤详解(附Axure RP原型设计与汉化教程)
ui·axure·photoshop