简体   繁体   English

使用 WPF 组件缩短重复性异常处理

[英]Shorten repetitive exception handling with WPF components

I am working with the WPF project, it's kinda annoying to have the same repetitive exception handling that only number makes it different?我正在使用 WPF 项目,有相同的重复异常处理有点烦人,只有数字使它不同?

Here's the code:这是代码:

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

As you can see the only thing changed is the number at the back that represents each component.如您所见,唯一改变的是后面代表每个组件的数字。 I know how to change the index of the array using loops, but how do I change the number at the back of the component name programmatically?我知道如何使用循环更改数组的索引,但是如何以编程方式更改组件名称后面的数字?

You don't need the try/catch at all.你根本不需要try/catch

Just use an ItemsControl with an appropriate ItemTemplate.只需将 ItemsControl 与适当的 ItemTemplate 一起使用。

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

and assign the models collection to its ItemsSource:并将models集合分配给它的 ItemsSource:

itemsControl.ItemsSource = models;

Note that the model members must be public properties.请注意,model 成员必须是公共属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM