Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 缩短WPF组件的重复异常处理_C#_Wpf - Fatal编程技术网

C# 缩短WPF组件的重复异常处理

C# 缩短WPF组件的重复异常处理,c#,wpf,C#,Wpf,我正在处理WPF项目,有点烦人,重复的异常处理只有数字让它不同 代码如下: 试试看 { 填充头模型1.Text=models[0]。模型; 填充头类型1.Text=“1.”+模型[0]。类型; 填充头子类型1.Text=models[0]。子类型; 填充头图像1.Source=defaultImage; } 捕获(IndexOutOfRangeException) { 填充头模型1.Text=null; 填充头类型1.Text=null; 填充头1.Text=null; 填充头图像1.Sour

我正在处理WPF项目,有点烦人,重复的异常处理只有数字让它不同

代码如下:

试试看
{
填充头模型1.Text=models[0]。模型;
填充头类型1.Text=“1.”+模型[0]。类型;
填充头子类型1.Text=models[0]。子类型;
填充头图像1.Source=defaultImage;
} 
捕获(IndexOutOfRangeException)
{
填充头模型1.Text=null;
填充头类型1.Text=null;
填充头1.Text=null;
填充头图像1.Source=null;
}
尝试
{
填充头模型2.Text=模型[1]。模型;
填充头类型2.Text=“2.”+模型[1]。类型;
填充头子类型2.Text=模型[1]。子类型;
填充头图像2.Source=defaultImage;
}
捕获(IndexOutOfRangeException)
{
填充头模型2.Text=null;
填充头类型2.Text=null;
填充头2.Text=null;
填充头图像2.Source=null;
}
... // 还有5个

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

您根本不需要
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>

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

而不是
try/catch
,您只需检查即可。一般情况下,对于意外情况,只应使用
try/catch
。在这里,您可以看到可能缺少的项目。将组件放入数组也是个好主意,谢谢@ErnoSure,我会试试@sinatr将UI元素放入数组是个糟糕的主意。一般来说,尤其是因为四种不同类型需要四个数组。
itemsControl.ItemsSource = models;