2014-06-16 4 views
1

주로 숫자 값의 데이터 캡처를 수행하는 응용 프로그램이 있습니다. 일반적으로 텍스트 상자를 사용하고 있습니다. 이 텍스트를 정리하기 위해 입력 한 숫자를 그룹화하고 그룹 사이에 공백을 넣기로했습니다.TextChanged 함수를 사용할 여러 TextBox의 클래스에 넣기

'555555555'와 같이 '555 555 555'처럼 표시되어 whatsapp 또는 viber signup 텍스트 상자 효과와 비슷한 것을 제공합니다. 이 작업을 수행하려면 TextChanged 이벤트를 사용하고 있습니다.

여기까지 내가 지금까지 해본 방법의 예입니다. 이것은 전화 번호를 입력 할 수있는 텍스트 상자입니다.

private void cell_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     string phrase = cell.Text; 
     if (phrase != null) 
     { 
      // This is to reset all spaces in the text back to none before the code below puts new ones. 
      // This avoids puting a space directly next to another one previously set. 
      // For some reason the textbox becomes difficult to work with if I don't do this. 
      phrase = Regex.Replace(phrase, @"\s+", ""); 
     } 

     // If the text is smaller than 4 characters; 
     if (phrase.Length <= 4) 
     { 
      // Do nothing to it 
      cell.Text = phrase; 
     } 

     // if the text is equal to five characters 
     if (phrase.Length == 5) 
     { 
      // group the first 3 characters 
      string first = phrase.Substring(0, 3); 
      // and the last 2 to characters 
      string second = phrase.Substring(3, 2); 

      // then put a space between them 
      string paste = (first + " " + second); 
      //This string goes into the TextBox 'cell' 
      cell.Text = paste; 
     } 

     // if the text is equal to six characters 
     if (phrase.Length == 6) 
     { 
      // group the first 3 characters 
      string first = phrase.Substring(0, 3); 

      //And the last 3 characters 
      string second = phrase.Substring(3, 3); 

      // then put a space between them 
      string paste = (first + " " + second); 
      //This string goes into the TextBox 'cell' 
      cell.Text = paste; 
     } 

     if (phrase.Length == 7) 
     { 
      // group the first 4 characters 
      string first = phrase.Substring(0, 4); 
      // then the next 3 
      string second = phrase.Substring(4, 3); 

      // then put a space between them 
      string paste = (first + " " + second); 
      //This string goes into the TextBox 'cell' 
      cell.Text = paste; 
     } 

     if (phrase.Length == 8) 
     { 
      // group the first 4 characters 
      string first = phrase.Substring(0, 4); 
      // then the next 3 
      string second = phrase.Substring(4, 3); 
      // then the next character 
      string third = phrase.Substring(7, 1); 

      // then put a space between the first, second and third string 
      string paste = (first + " " + second + " " + third); 
      //This string goes into the TextBox 'cell' 
      cell.Text = paste; 
     } 

     if (phrase.Length == 9) 
     { 
      // group the first 4 characters 
      string first = phrase.Substring(0, 4); 
      // then the next 3 
      string second = phrase.Substring(4, 3); 
      // then the next 2 characters 
      string third = phrase.Substring(7, 2); 

      // then put a space between the first, second and third string 
      string paste = (first + " " + second + " " + third); 
      //This string goes into the TextBox 'cell' 
      cell.Text = paste; 
     } 

     if (phrase.Length == 10) 
     { 
      // group the first 4 characters 
      string first = phrase.Substring(0, 4); 
      // then the next 3 
      string second = phrase.Substring(4, 3); 
      // then the next 3 characters after that 
      string third = phrase.Substring(7, 3); 

      // then put a space between the first, second and third string 
      string paste = (first + " " + second + " " + third); 
      //This string goes into the TextBox 'cell' 
      cell.Text = paste; 
     } 

     //This is to keep the cursor at the end of the TextBox's text when I enter a new character other wise it goes back to the start. 
     cell.CaretIndex = cell.Text.Length; 
    } 

문제는 우선이 코드는 내가 (내 강사가 이미 이런 일을 반복했다 나쁜 연습과 I 언급 번호를 구분해야하는 모든 텍스트 상자에 배치 할 여유가 없다 너무 오래입니다 그것을 위해 벌을받을지도 모른다). 그러나 나는 이것을 할 수 있어야하는 많은 세포를 가지고있다. 그러나 나는 그것을 행동으로 바꾸거나 그것을 클래스에 넣고 여전히 기능하게하는 기술이 부족하다.

그래서 기본적으로 내가 알고 싶은 것은 여러 페이지에 걸쳐 사용되는 get, set 클래스 또는 behavior 클래스 (또는 그 문제에 대해 간과 할 수있는 anyother)에서이를 구현하는 방법입니다. 누구 제안?

+1

코드를 별도의 메서드로 추출하고 해당 메서드를 처리기에서 호출하십시오. –

+1

요구 사항이 맞으면 Mvvm Approach [StackReference] (http://stackoverflow.com/questions/20089739/wpf-mvvm-textbox-text-binding-vs-changedtext-event)에서이 작업을 수행하면 성능이 현저하게 향상됩니다 너무. – Eldho

+0

그러면 도움이 될 것입니다 : 'for (int i = 3; i franssu

답변

1

어떤 UI 컨트롤에 일부 코드를 캡슐화하는 가장 간단한 방법은 연결된 속성을 선언하는 것입니다 ...그것은 기존 UI 요소의 기능을 확장하는 것입니다. 첨부 된 속성에 익숙하지 않다면 MSDN의 Attached Properties Overview 페이지에서 자세한 내용을 볼 수 있습니다. 여기

당신이 사용할 수있는 예제가 ... 당신이해야 할 모든 이벤트 핸들러를 추가하는 것입니다 :

public static readonly DependencyProperty IsFormattedProperty = DependencyProperty.RegisterAttached("IsFormatted", typeof(bool), typeof(TextBoxProperties), new UIPropertyMetadata(default(bool), OnIsFormattedChanged)); 

public static bool GetIsFormatted(DependencyObject dependencyObject) 
{ 
    return (bool)dependencyObject.GetValue(IsFormattedProperty); 
} 

public static void SetIsFormatted(DependencyObject dependencyObject, bool value) 
{ 
    dependencyObject.SetValue(IsFormattedProperty, value); 
} 

public static void OnIsFormattedChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) 
{ 
    TextBox textBox = dependencyObject as TextBox; 
    if (textBox != null) 
    { 
     bool newIsFormattedValue = (bool)dependencyPropertyChangedEventArgs.NewValue; 
     if (newIsFormattedValue) textBox.TextChanged += YourTextChangedHandler; 
     else textBox.TextChanged -= YourTextChangedHandler; 
    } 
} 

그것은 TextBoxProperties라는 이름의 클래스에 추가되어야하며, 단순히으로 사용된다 this :

<TextBox TextBoxProperties:IsFormatted="True" ... /> 
+0

안녕하세요. 내가 물을 수 있다면, 나는 어떻게 그 사건을 정의 하겠는가? 나는'공개 무효 YourTextChangedHandler (객체 발신자, TextChangedEventHandler routedEventArgs)'및'public void YourTextChangedHandler (객체 발신자, RoutedEventArgs routedEventArgs)'를 시도했지만 그 내용은 – Offer

+0

응용 프로그램과 유사하지 않습니다. 정적 메서드에서 정적이 아닌 속성을 호출하는 것 같습니다. 내 잘못. 이것은 잘 작동했습니다. 수업에도 많은 감사를드립니다. – Offer

1

cell_TextChanged에서 코드를 추출하여 새로운 방법으로 옮겨야합니다. 그런 다음 이벤트 처리기에서이 새 메서드를 호출합니다.

private void cell_TextChanged(object sender, TextChangedEventArgs e) 
{ 
    YourTextChangedHandlerMethod(sender as TextBox, e); 
} 

이 접근법은 동일한 코드를 다시 사용하기 때문에 각 이벤트에 대해 동일한 코드를 작성할 필요가 없음을 의미합니다. YourTextChangedHandlerMethod의 첫 번째 매개 변수는 이벤트를 발생시킨 텍스트 상자입니다.

새로운 방법에 필요한 매개 변수를 강화할 수 있지만 알아낼 수있는 간단한 방법이 있습니다. 다른 속성과 뷰 모델에

1. 바인딩이 같은 방법을 호출

+0

알았어. 새로운 방법으로 cell.text가 아닌 텍스트 상자의 텍스트를 받아들이는 방법은 무엇입니까? 그리고 그것을 '트리거링 한 텍스트 상자에'붙여 넣기 '문자열을 반환해야한다고 어떻게 알 수 있습니까? – Offer

+0

나는 방금 희망을 갖고 도움이되는 대답에 대한 작은 업데이트를 만들었다. 'sender' 매개 변수는 이벤트를 발생시킨 컨트롤이므로 텍스트 상자를 다루는 것만으로 어떤 텍스트 상자가 이벤트를 발생시키는 지 신경 쓰지 않습니다. 당신은 분명히 당신의 새로운 메소드에서'cell'의 이름을 좀 더 일반적인 것으로 변경해야합니다. –

+0

안녕하세요. 다른 질문. '발신자'의 값을 'phrase'문자열에 전달하는 방법은 무엇입니까? 'string phrase = cell.Text'가 나오기 전에. 그것은'string phrase = sender'가 작동하지 않을 것 같고'sender.ToString' 캐스트도 ... 나는 여전히 그걸 잃어버린 것 같아요. 미안하다. 내가 더 명백한 무엇인가 있어야하는 무엇인가 묻고 있으면. 나는 당신이 '셀'의 이름을 바꾸라고 말했을 때 이것을 언급했을 수도 있습니다. – Offer

0

당신은 당신이 그 옵션 중 하나를 사용할 수 있습니다 MVVM의 방법으로 그것을 수행합니다. UpdateSourceTrigger

<TextBox Text="{Binding MyText, ElementName=myControl, UpdateSourceTrigger=PropertyChanged}"/> 

을 지정하거나 텍스트 상자가의 TextChanged 명령을 지원하기 위해 자신의 연결된 동작을 작성하는 것을 잊지 마십시오. 당신이 MVVM을 다음하지 않는 경우에 당신이 뭔가를 사용할 수 있습니다

<TextBox x:Name="SomeText"> 
    <interactivity:Interaction.Triggers> 
    <interactivity:EventTrigger EventName="TextChanged"> 
     <interactivity:InvokeCommandAction Command="{Binding SomeCommand, Mode=OneWay}"/> 
    </interactivity:EventTrigger> 
    </interactivity:Interaction.Triggers>   
</TextBox> 
+0

나는 TextChanged에 대해 당신이 Propertychanged에 대해 UpdateSourceTrigger를 사용할 수 있기 때문에 대화 형 기능을 사용할 필요가 없다고 생각합니다. – Eldho

+0

나는 세 가지 옵션 중 하나를 사용할 수 있습니다. :). 수정 된 답변 – user1153896

+0

괜찮아요, 근데 가장 좋은 방법이 먼저라고 생각합니다. – Eldho

0

System.Windows.Interactivity에서

3. 또는 사용 InvokeCommandAction는 같은 방법으로 결합합니다.

class FindingLogicalChildren 
{ 
    public static IEnumerable<T> FindVisualChildren<T>(DependencyObject dependencyObject) where T : DependencyObject 
    { 
     if (dependencyObject != null) 
     { 
      for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++) 
      { 
       DependencyObject child = VisualTreeHelper.GetChild(dependencyObject, i); 
       if (child != null && child is T) 
       { 
        yield return (T)child; 
       } 

       foreach (T childOfChild in FindVisualChildren<T>(child)) 
       { 
        yield return childOfChild; 
       } 
      } 

     } 

    } 

및로드 당신의 MainWindow를에

mainwindow.xaml

private void window_Loaded(object sender, RoutedEventArgs e) 
    { 
     foreach (TextBox it in FindingLogicalChildren.FindVisualChildren<TextBox>(Application.Current.MainWindow)) 
     { 
      t = it; 
      t.TextChanged += t_TextChanged; 
     } 
} 

void t_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     // do your work here.. you get all textchanged events here  
    } 
관련 문제