如何使这个代码更有效?

时间:2013-06-17 12:20:05

标签: c# wpf properties

由于我在C#方面还不是很先进,我尝试学习如何提高代码效率。 我在一些属性中存储了很多字符串。

在应用程序开始时,我将所有seperatie属性加载到文本框中。 我现在是这个代码加载所有:

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;
}

很明显,我可以看到每个以T1L1结尾的存储属性也适合以T1S1结尾的txt的逻辑。 我只知道这应该以比我现在更优雅和坚实的方式完成。 有人能把我推向正确的方向吗?

2 个答案:

答案 0 :(得分:5)

您可以将属性直接绑定到文本框

<UserControl xmlns:Properties="clr-namespace:MyProjectNamespace.Properties" >


<TextBox Text="{Binding Source={x:Static Properties:Settings.Default}, Path=strT1L1, Mode=TwoWay}" />

答案 1 :(得分:0)

如果您可以将所有这些常量都放入List<string>,则可以使用它来绑定ItemsControl内的TextBlock

代码隐藏或查看模型

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>