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

kxe2p93d  于 2022-12-14  发布在  其他
关注(0)|答案(1)|浏览(165)

我尝试建立自订使用者控件,特别是自订TextBox,它会将使用者输入的文字转换成大写,并显示在控件中。但是,我无法让它运作。以下是我的程式码:

自定义文本框用户控件:

<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}}"/>

用户控件的代码隐藏:

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(""));

用法:

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

转换器:

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();
      }
   }

我需要做哪些更改才能使这个自定义TextBox按预期工作?

bqf10yzr

bqf10yzr1#

需要添加绑定Path=Text:

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

并在使用者控件建构函式中,将DataContext设定为:

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

相关问题