簡體   English   中英

使用 WPF 組件縮短重復性異常處理

[英]Shorten repetitive exception handling with WPF components

我正在使用 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

如您所見,唯一改變的是后面代表每個組件的數字。 我知道如何使用循環更改數組的索引,但是如何以編程方式更改組件名稱后面的數字?

你根本不需要try/catch

只需將 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>

並將models集合分配給它的 ItemsSource:

itemsControl.ItemsSource = models;

請注意,model 成員必須是公共屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM