2015-09-22 1 views
0

У меня есть AutoCompleteBox как DataGrid Тип столбца. Например:Как преобразовать wpf AutoCompleteBox ко всем вводам верхнего регистра

<DataGridTemplateColumn> 
    <DataGridTemplateColumn.CellTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding Path=Thing, UpdateSourceTrigger=PropertyChanged}" /> 
     </DataTemplate> 
    </DataGridTemplateColumn.CellTemplate> 

    <DataGridTemplateColumn.CellEditingTemplate> 
     <DataTemplate> 
      <SLToolkit:AutoCompleteBox Text="{Binding Path=Thing, 
               UpdateSourceTrigger=PropertyChanged}" /> 
     </DataTemplate> 
    </DataGridTemplateColumn.CellEditingTemplate> 
</DataGridTemplateColumn> 

Однако я хочу ограничить ввод пользователя в верхнем регистре. На TextBoxes Я могу сделать это следующим образом, но я не могу получить это для работы с AutoCompleteBoxes.

<DataGridTextColumn Binding="{Binding UpdateSourceTrigger=PropertyChanged, Path=Thing}"> 
    <DataGridTextColumn.EditingElementStyle> 
     <Style TargetType="TextBox"> 
      <Setter Property="CharacterCasing" Value="Upper" /> 
     </Style> 
    </DataGridTextColumn.EditingElementStyle> 
</DataGridTextColumn> 

Я попытался это:

<SLToolkit:AutoCompleteBox Text="{Binding Path=Thing, 
              UpdateSourceTrigger=PropertyChanged}" 
          TextChanged="AutoComplete_TextChanged" /> 

С этим:

private void AutoComplete_TextChanged(object sender, RoutedEventArgs e) 
{ 
    AutoCompleteBox box = sender as AutoCompleteBox; 
    if (box == null) return; 
    box.Text = box.Text.ToUpper(); 
} 

Такого рода работ кроме того, что он пишет в обратном направлении. Когда пользователь вводит символ, курсор возвращается к началу окна, поэтому следующее слово находится перед предыдущим. Если бы я написал «пример», я бы увидел «ELPMAXE».

Любые идеи?

ответ

0

Я решил аналогичную проблему, когда мне хотелось только ввести числа в текстовое поле, поэтому я использовал поведение. Если вводится не номер, символ удаляется. Я также использовал библиотеку интерактивности, которая использует System.Windows.Interactivity.dll (просто импортируйте эту DLL в свой проект, если у вас нет ее части blend sdk http://www.microsoft.com/en-us/download/details.aspx?id=10801).

Вот упрощенная XAML:

<Window x:Class="Sample.SampleWindow" 
      xmlns:main="clr-namespace:MySampleApp" 
      xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
      Title="Sample" 
      Height="800" 
      Width="1025" 
      > 
         <Grid> 
          <TextBox Text="{Binding Path=Entry, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
            Width="30" 
            MaxLength="4" 
            HorizontalAlignment="Left"> 
           <i:Interaction.Behaviors> 
            <main:KeyPressesWithArgsBehavior 
KeyUpCommand="{Binding KeyUpFilterForUpperCaseSymbols}" /> 
           </i:Interaction.Behaviors> 
          </TextBox> 
         </Grid> 
    </Window> 

использует следующий класс Behavior:

public class KeyPressesWithArgsBehavior : Behavior<UIElement> 
{ 
    #region KeyDown Press DependencyProperty 
    public ICommand KeyDownCommand 
    { 
     get { return (ICommand) GetValue(KeyDownCommandProperty); } 
     set { SetValue(KeyDownCommandProperty, value); } 
    } 

    public static readonly DependencyProperty KeyDownCommandProperty = 
     DependencyProperty.Register("KeyDownCommand", typeof (ICommand), typeof (KeyPressesWithArgsBehavior)); 

    #endregion KeyDown Press DependencyProperty 

    #region KeyUp Press DependencyProperty 

    public ICommand KeyUpCommand 
    { 
     get { return (ICommand) GetValue(KeyUpCommandProperty); } 
     set { SetValue(KeyUpCommandProperty, value);} 
    } 

    public static readonly DependencyProperty KeyUpCommandProperty = 
     DependencyProperty.Register("KeyUpCommand", typeof(ICommand), typeof (KeyPressesWithArgsBehavior)); 

    #endregion KeyUp Press DependencyProperty 

    protected override void OnAttached() 
    { 
     AssociatedObject.KeyDown += new KeyEventHandler(AssociatedUIElementKeyDown); 
     AssociatedObject.KeyUp += new KeyEventHandler(AssociatedUIElementKeyUp); 
     base.OnAttached(); 
    } 

    protected override void OnDetaching() 
    { 
     AssociatedObject.KeyDown -= new KeyEventHandler(AssociatedUIElementKeyDown); 
     AssociatedObject.KeyUp -= new KeyEventHandler(AssociatedUIElementKeyUp); 
     base.OnDetaching(); 
    } 

    private void AssociatedUIElementKeyDown(object sender, KeyEventArgs e) 
    { 
     if (KeyDownCommand != null) 
     { 
      ObjectAndArgs oa = new ObjectAndArgs {Args = e, Object = AssociatedObject}; 
      KeyDownCommand.Execute(oa); 
     } 
    } 

    private void AssociatedUIElementKeyUp(object sender, KeyEventArgs e) 
    { 
     if (KeyUpCommand != null) 
     { 
      KeyUpCommand.Execute(AssociatedObject); 
     } 
    } 
} 

Затем в виде модели можно реализовать команду. SampleWindowViewModel.cs:

public ICommand KeyUpFilterForUpperCaseSymbolsCommand 
    { 
     get 
     { 
      if (_keyUpFilterForUpperCaseSymbolsCommand== null) 
      { 
       _keyUpFilterForUpperCaseSymbolsCommand= new RelayCommand(KeyUpFilterForUpperCaseSymbols); 
      } 
      return _keyUpFilterForUpperCaseSymbolsCommand; 
     } 
    } 

...

private void KeyUpFilterForUpperCaseSymbols(object sender) 
    { 
     TextBox tb = sender as TextBox; 
     if (tb is TextBox) 
     { 
      // check for a lowercase character here 
      // then modify tb.Text, to exclude that character. 
      // Example: tb.Text = oldText.Substring(0, x); 
     } 
    } 
Смежные вопросы