如何解决缩短WPF组件的重复异常处理
我正在与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;
请注意,模型成员必须是公共属性。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。