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

相关推荐
闲云自留地4 小时前
OpenStack 的身份管家:Keystone 令牌、RBAC 权限模型拆解
wpf·openstack
web守墓人5 小时前
【goed/ui】go开发windows原生应用之Helloworld篇
windows·ui·golang
FuckPatience2 天前
WPF 窗体唤醒,判断是否已存在,存在则弹出
wpf
程序员清风2 天前
从单体应用到微服务:后端系统拆分的基本方法
微服务·架构·wpf
码匠许师傅3 天前
【设计模式精讲】25.状态模式(State)
c++·ui·设计模式·状态模式·uml
FuckPatience3 天前
WPF 改变根据某一列条件改变行样式
wpf
插件开发4 天前
Illustrator 插件开发:链接文件存在检查的原理与实战
ui·illustrator
xy34534 天前
axure9.0 如何打造一个计时器(简单版)
前端·ui·html·axure·原型·产品设计
dalong104 天前
WPF:DataGrid样式
wpf
图扑软件4 天前
下篇・换墨|主题/多语言/移动端,一套组件全覆盖
前端·javascript·ui·性能优化·数据可视化