2015-01-27 3 views
0

Я создал экземпляр TextBox, который реализует ICommandSource, я хотел бы управлять свойством IsEnabled через DataContext. Эта часть моего кода работает, помимо этого я хотел бы управлять свойством Text с помощью этого же метода или расширением свойства IsEnabled.Использование переопределения в UserControl для изменения разрывов свойств Триггер

В основном, когда TextBox переходит из IsEnabled = "False" в IsEnabled = "True" Я хотел бы сбросить текстовое поле на пустую строку или, желательно, на null.

Я попытался сделать это несколькими путями без успеха.

Покушение 1

<ctrl:CommandTextBox x:Name="txtSerialNumber" 
        Command="{Binding VMFactory.CreateViewModelCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" 
        CommandParameter="{Binding Text, RelativeSource={RelativeSource Self}}" DecoderPrefix="S"> 
    <ctrl:CommandTextBox.Style> 
     <Style TargetType="{x:Type ctrl:CommandTextBox}"> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding}" Value="{x:Null}"> 
        <Setter Property="IsEnabled" Value="True" /> 
        <Setter Property="Text" Value="{x:Null}" /> 
       </DataTrigger> 
      </Style.Triggers> 
      <Setter Property="IsEnabled" Value="False" /> 
      <Setter Property="Text" Value="{Binding SerialNumber, Mode=OneWay}" /> 
     </Style> 
    </ctrl:CommandTextBox.Style> 
</ctrl:CommandTextBox> 

Это делает работу, но только тогда, когда CommandParameter не нужно быть "Раскодированный". Кажется, что когда мое свойство текста изменяется с помощью переопределения, он прерывает триггер до тех пор, пока приложение не будет перезапущено.

CommandTextBox.cs

public class CommandTextBox : DecoderTextBox, ICommandSource 
{ 
    // Additional Fields, Properties, and Methods removed for the sake of brevity. 

    protected override void OnKeyDown(KeyEventArgs e) 
    { 
     base.OnKeyDown(e); 

     if (e.Key == Key.Enter && Command != null) 
     { 
      RoutedCommand command = Command as RoutedCommand; 

      if (command != null) 
       command.Execute(CommandParameter, CommandTarget); 
      else 
       Command.Execute(CommandParameter); 

      if (CommandResetsText) 
       this.Text = String.Empty; 

      e.Handled = true; 
     } 
    } 
} 

DecoderTextBox.cs

public class DecoderTextBox : TextBox 
{ 
    public static DependencyProperty DecoderPrefixProperty = DependencyProperty.Register("DecoderPrefix", typeof(string), typeof(DecoderTextBox), new PropertyMetadata(String.Empty)); 

    public string DecoderPrefix 
    { 
     get { return (string)GetValue(DecoderPrefixProperty); } 
     set { SetValue(DecoderPrefixProperty, value); } 
    } 

    protected override void OnKeyDown(KeyEventArgs e) 
    { 
     if (e.Key == Key.Enter) 
     { 
      string text = this.Text; 

      // If the if statement returns true the trigger will break. 
      if (text.Substring(0, Math.Min(DecoderPrefix.Length, text.Length)) == DecoderPrefix) 
       this.Text = text.Remove(0, DecoderPrefix.Length); 
     } 

     base.OnKeyDown(e); 
    } 
} 

Есть ли что-то конкретное для моей реализации OnKeyDown, что нарушает этот триггер?

+0

вопрос, ваш 'CommandTextBox' внутри шаблона любой шанс? – XAMlMAX

+0

@XAMlMAX Нет, это не так, он сидит внутри сетки, которая является частью UserControl. –

+0

ok, если любые части визуального дерева, к которому это принадлежит, не являются шаблонами, тогда должен применяться стиль. Что вы получаете в окне вывода? Не может ли это найти? – XAMlMAX

ответ

0

Существует проблема, связанная с установкой значения свойства DependencyProperty локально. Кажется, вы должны использовать SetCurrentValue для сохранения привязки.

DecoderTextBox.cs

protected override void OnPreviewKeyDown(KeyEventArgs e) 
{ 
    if (e.Key == Key.Enter) 
    { 
     if (Text.StartsWith(DecoderPrefix)) 
      SetCurrentValue(TextProperty, Text.Remove(0, DecoderPrefix.Length)); 
    } 

    base.OnPreviewKeyDown(e); 
} 
Смежные вопросы