简体   繁体   English

自定义TextBox用户控件在WPF中实现转换器

[英]Custom TextBox user control implementing a converter in WPF

I'm trying to build a Custom User Control , a custom TextBox to be exact. 我正在尝试构建自定义用户控件 ,确切地说是自定义TextBox The idea is as the user types in the TextBox the text is converted to uppercase and displayed. 这个想法是用户在TextBox键入文本转换为大写并显示。 But I cannot get it to work. 但我无法让它发挥作用。

CustomTextBox UserControl: CustomTextBox UserControl:

<UserControl x:Class="SOFWpf.CustomTextBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:converters="clr-namespace:SOFWpf.Converters"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <converters:CaseConverter x:Key="CaseConverter" />
    </UserControl.Resources>

    <TextBox Text="{Binding Path=., Converter={StaticResource CaseConverter}}"/>

UserControl's Code-Behind: UserControl的代码背后:

  public string Text
  {
     get { return (string)GetValue(TextProperty); }
     set { SetValue(TextProperty, value); }
  }

  public static readonly DependencyProperty TextProperty =
      DependencyProperty.Register("Text", typeof(string), typeof(CustomTextBox), new UIPropertyMetadata(""));

Usage: 用法:

<local:CustomTextBox Text="a b c"/>

Converter: 转换器:

   public class CaseConverter : IValueConverter
   {
      public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
         string text = value as string;

         return text?.ToUpper();
      }

      public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
         string text = value as string;

         return text?.ToLower();
      }
   }

You need to add binding Path=Text: 您需要添加绑定Path = Text:

<TextBox Text="{Binding Path=Text, Converter={StaticResource CaseConverter}}"/>

And in the user control constructor set DataContext to this: 并在用户控件构造函数中将DataContext设置为:

public CustomTextBox()
{
    InitializeComponent();
    DataContext = this;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM