【问题标题】:Custom TextBox user control implementing a converter in WPF在 WPF 中实现转换器的自定义 TextBox 用户控件
【发布时间】:2017-07-19 09:35:01
【问题描述】:

我正在尝试构建一个自定义用户控件,确切地说是自定义TextBox。这个想法是当用户键入TextBox 时,文本被转换为大写并显示。但我无法让它工作。

CustomTextBox 用户控件:

<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 的代码隐藏:

  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 的 Text 属性绑定到 UserControl 的属性,例如 &lt;TextBox Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}, ...}" /&gt;
  • @Vahid 将 Mode=TwoWay 和 UpdateSourceTrigger 设置为 PropertyChanged
  • @WPFUser 成功了!

标签: c# wpf data-binding user-controls dependency-properties


【解决方案1】:

你需要添加绑定Path=Text:

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

并在用户控件构造函数中将 DataContext 设置为:

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

【讨论】: