【问题标题】:How to make this code more efficient?如何让这段代码更有效率?
【发布时间】:2013-06-13 09:30:47
【问题描述】:

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

在应用程序开始时,我将所有单独的属性加载到文本框中。 我现在用这段代码来加载它们:

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 的逻辑。 我只知道这应该以比我现在所做的更优雅和更可靠的方式来完成。 谁能把我推向正确的方向?

【问题讨论】:

  • 有一条经验法则:“如果你必须做三遍以上的事情,请使用循环”(左右)。同样在这里,使用一个类似列表的容器(例如ListBox),里面只有一个TextBlock,并且(最好)将集合绑定到ListBox。假设您还可以将字符串作为某种集合写入设置。
  • mm 我不确定,肯定可以放入字段中,然后将它们保存回属性,所以下次他加载应用程序时,更改的字符串会再次加载。
  • 我是一个“winforms”的人,所以我在 WPF 中做的不多。但在 winforms 中,您可以将控件的属性(在本例中为 .Text)绑定到应用程序设置。

标签: c# wpf properties


【解决方案1】:

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

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


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

【讨论】:

  • 我在这段代码中遇到了一些错误。我需要在第一个 } 后面放一个 ,。之后,我收到一条错误消息,提示“找不到类型属性:设置”。在标记扩展的关闭 } 之后,它的说法“路径”也是不允许的
  • 它说它有两种工作方式,但是当我只是更改线路并重新启动应用程序时。没有保存?
  • 如果你想保存你的东西,你必须调用 Properties.Settings.Default.Save();至少在关闭或 Application.Exit 事件中
【解决方案2】:

如果您可以将所有这些常量放入List&lt;string&gt;,您可以使用它绑定到带有TextBlockItemsControl

代码隐藏或查看模型

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-22
    • 2015-08-31
    • 1970-01-01
    • 2012-04-01
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多