How to make this code more efficient?

As I am still not very advanced in C #, I am trying to learn how to make my code more efficient. I saved a lot of lines in some properties.

At the beginning of the application, I load all seperatie properties into text fields. Now I use this code to download all of them:

private void LoadStoredStrings() { txtT1S1.Text = Properties.Settings.Default.strT1L1; txtT1S2.Text = Properties.Settings.Default.strT1L2; txtT1S3.Text = Properties.Settings.Default.strT1L3; txtT1S4.Text = Properties.Settings.Default.strT1L4; txtT1S5.Text = Properties.Settings.Default.strT1L5; txtT1S6.Text = Properties.Settings.Default.strT1L6; txtT1S7.Text = Properties.Settings.Default.strT1L7; txtT1S8.Text = Properties.Settings.Default.strT1L8; txtT1S9.Text = Properties.Settings.Default.strT1L9; txtT1S10.Text = Properties.Settings.Default.strT1L10; } 

Obviously, I see the logic that every saved property ending in T1L1 is also suitable for txt that ends in T1S1 . I just know that this should be done in a more elegant and reliable way than what I have done now. Can someone push me in the right direction?

+4
source share
2 answers

you can bind your properties directly to your text fields

 <UserControl xmlns:Properties="clr-namespace:MyProjectNamespace.Properties" > <TextBox Text="{Binding Source={x:Static Properties:Settings.Default}, Path=strT1L1, Mode=TwoWay}" /> 
+5
source

If you can get all of these constants in a List<string> , you can use it to bind to an ItemsControl with a TextBlock inside:

Code Behind or View Model

 private ObservableCollection<string> _defaultProperties = new ObservableCollection<string>(); public ObservableCollection<string> DefaultProperties { get { return _defaultProperties; } } 

Xaml

 <ListBox ItemsSource="{Binding Path=DefaultProperties"}> <ListBox.ItemTemplate> <DataTemplate> <!--Just saying "Binding" allows binding directly to the current data context vs. a property on the data context--> <TextBlock Text="{Binding}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 
0
source

Source: https://habr.com/ru/post/1486613/


All Articles