【问题标题】:Shorten repetitive exception handling with WPF components使用 WPF 组件缩短重复性异常处理
【发布时间】:2020-12-06 12:38:52
【问题描述】:

我正在与 WPF 项目合作,有相同的重复异常处理,只有数字使它不同,这有点烦人?

代码如下:

try
{
    filling_head_model1.Text = models[0].Model;
    filling_head_type1.Text = "1. " + models[0].Type;
    filling_head_subtype1.Text = models[0].SubType;
    filling_head_image1.Source = defaultImage;
} 
catch (IndexOutOfRangeException)
{
    filling_head_model1.Text = null;
    filling_head_type1.Text = null;
    filling_head_subtype1.Text = null;
    filling_head_image1.Source = null;
}

try
{
    filling_head_model2.Text = models[1].Model;
    filling_head_type2.Text = "2. " + models[1].Type;
    filling_head_subtype2.Text = models[1].SubType;
    filling_head_image2.Source = defaultImage;
}
catch (IndexOutOfRangeException)
{
    filling_head_model2.Text = null;
    filling_head_type2.Text = null;
    filling_head_subtype2.Text = null;
    filling_head_image2.Source = null;
}
... // there are 5 more

如您所见,唯一改变的是后面代表每个组件的数字。我知道如何使用循环更改数组的索引,但是如何以编程方式更改组件名称后面的数字?

【问题讨论】:

  • 您可以简单地检查if such index exists,而不是try/catch。一般而言,您应该只将try/catch 用于意外。在这里,您预计可能缺少什么项目。
  • 将组件也放入数组中
  • 好主意,谢谢@Erno
  • 肯定会试试@Sinatr
  • 将 UI 元素放在一个数组中是一个糟糕的主意。一般来说,特别是因为您需要针对四种不同类型的四个数组。

标签: c# wpf


【解决方案1】:

您根本不需要try/catch

只需使用带有适当 ItemTemplate 的 ItemsControl。

<ItemsControl x:Name="itemsControl">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Model}"/>
                <TextBlock>
                    <Run Text="{Binding Number}"/><Run Text="."/>
                    <Run Text="{Binding Type}"/>
                </TextBlock>
                <TextBlock Text="{Binding SubType}"/>
                <Image Source="{Binding Image}"/>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>    
</ItemsControl>

并将models 集合分配给它的ItemsSource:

itemsControl.ItemsSource = models;

注意模型成员必须是公共属性。

【讨论】:

    猜你喜欢
    • 2010-11-12
    • 2015-08-19
    • 2010-12-01
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多