2016-07-14 10 views
1

код в контекстеизменения «IsEnabled» для МОФ texbox в UserControl (коде)

private void button2_Click(object sender, RoutedEventArgs e) 
    { 
     edit(); 
    } 

    public void edit() 
    { 

     textBox1.IsEnabled = true; 
     textBox2.IsEnabled = true; 
     textBox3.IsEnabled = true; 
     textBox4.IsEnabled = true; 
     textBox5.IsEnabled = true; 
     textBox6.IsEnabled = true; 
     textBox7.IsEnabled = true;    
     textBox8.IsEnabled = true; 
     textBox9.IsEnabled = true; 
     textBox10.IsEnabled = true; 
     textBox11.IsEnabled = true; 
     textBox12.IsEnabled = true; 
     textBox13.IsEnabled = true; 
     textBox14.IsEnabled = true; 
     textBox15.IsEnabled = true; 
     textBox16.IsEnabled = true; 
     textBox17.IsEnabled = true; 
     textBox18.IsEnabled = true; 
    } 

Я хочу, чтобы выполнить выше, используя простой цикл что петли через 1-18.

Я попытался followng метода, но не работает по назначению

for(i=0;i<19;i++) 
    { 
      textBox"" + i + "".IsVisible = true; 
    } 

Я новичок в WPF и я мигрирующий мое приложение из WinForms в WPF.

+0

Будет ли это работать в WinForms? Я вижу некоторый странный синтаксис 'textBox '" + i + "" .IsVisible = true; ' – Alex

ответ

3

Использовать привязку.

XAML (MyUserControl):

<UserControl Name="MyControl" ... 
.... 

    <TextBox Name="textBox1" IsEnabled="{Binding ElementName=MyControl, Path=AreTextBoxesEnabled}" ... /> 
    <TextBox Name="textBox2" IsEnabled="{Binding ElementName=MyControl, Path=AreTextBoxesEnabled}" ... /> 
    <TextBox Name="textBox3" IsEnabled="{Binding ElementName=MyControl, Path=AreTextBoxesEnabled}" ... /> 
... 

код-за (MyUserControl):

public static readonly DependencyProperty AreTextBoxesEnabledProperty = DependencyProperty.Register(
    "AreTextBoxesEnabled", 
    typeof(bool), 
    typeof(MyUserControl)); 

public bool AreTextBoxesEnabled 
{ 
    get { return (bool)GetValue(AreTextBoxesEnabledProperty); } 
    set { SetValue(AreTextBoxesEnabledProperty, value); } 
} 

Просто позвонив AreTextBoxesEnabled = true; сделает все текстовые поля включены.

Конечно, существует много других способов. Но это основной способ (без MVVM) сделать это, используя силу привязки.

Простое решение (но не рекомендуется) способ так же просто, как:

for (i = 0; i < 19; i++) 
{ 
    var tb = this.FindName("textBox" + i.ToString()) as TextBox; 
    if (tb != null) tb.IsEnabled = true; 
} 
+0

Согласовано, привязка - более естественное решение для WPF – Alex

+1

, изменяющее' DataContext' в UserControl - плохая идея. 'DataContext' - это пользовательские данные. гораздо лучше использовать RelativeSource или ElementName для привязки IsEnabled или TemplateBinding в ControlTemplate – ASh

+0

@ASh Согласен, у меня была эта проблема до ха-ха. – Jai

0

Создание списка текстовых полей, как:

var textBoxes = new List<TextBox>(); 

// Btw, у меня нет компилятора вручную, я предполагаю, что тип TextBox.

Заливка Textboxes:

textBoxes.Add(textBox1); 
textBoxes.Add(textBox2); 
... 
textBoxes.Add(textBox18); 

Это одноразовое ручные действия, чтобы заполнить его. После этого вы можете цикл через них:

foreach (var textBox in textBoxes) 
{ 
    textBox.IsVisible = true; 
} 

Или использовать любые другие настройки/алгоритм на текстовых полях с петлей Еогеасп (или, LINQ и т.д.).

 Смежные вопросы

  • Нет связанных вопросов^_^