WPF中Binding中使用Converter

案例:在WPF界面添加批次和数量,批次是通过物料码进行扫描得到,格式为 产品名称|批次|数量 现在需要扫描后直接显示批次

<DataGridTemplateColumn
    Width="*"
    CanUserResize="False"
    Header="批号">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBox
                    Width="400"
                    Height="40"
                    Text="{Binding Distnumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource SubstringConverter}}" />
            </StackPanel>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

这里的静态资源需要在APP中注册
确保你在 App.xaml 中正确注册了 SubstringConverter

<Application
    x:Class="BLWPFApp.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:converters="clr-namespace:BLWPFApp.Converters"
    xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
    xmlns:local="clr-namespace:BLWPFApp"
    xmlns:o="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options"
    StartupUri="PowdererLoginForm.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/MySkin/MySkin.xaml" />
                <ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml" />
                <ResourceDictionary Source="/MySkin/MergeTableDictionary.xaml" />
                <ResourceDictionary Source="/MySkin/ElementGroupDictionary.xaml" />
                <ResourceDictionary Source="/MySkin/DataGridDictionary.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <converters:SubstringConverter x:Key="SubstringConverter" />
        </ResourceDictionary>
    </Application.Resources>
</Application>

然后我们的类
SubstringConverter 类
首先,确保你的 SubstringConverter 类定义正确,并位于 BLWPFApp.Converters 命名空间中

using System;
using System.Globalization;
using System.Windows.Data;

namespace BLWPFApp.Converters
{
    public class SubstringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string strValue)
            {
                var parts = strValue.Split('|');
                if (parts.Length > 1)
                {
                    return parts[1]; // 返回字符串的第二部分
                }
            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

重要提示
确保资源键和引用一致:Converter={StaticResource SubstringConverter} 中的 SubstringConverter 必须与 App.xaml 中定义的资源键一致。
确保引用路径正确:命名空间引用 xmlns:converters=“clr-namespace:BLWPFApp.Converters” 应正确指向 SubstringConverter 所在的命名空间。
确保类和命名空间一致:确保 SubstringConverter 类的命名空间与引用路径一致

你可能感兴趣的:(wpf)