c# - 使用 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;
请注意,模型成员必须是公共属性。
推荐阅读
- php - 使用 iCal 对象的 PHP 会议邀请,结果约会不可编辑
- dns - cpanel:解决 ERR_NAME_NOT_RESOLVED
- javascript - 将 React Ref 从父级传递给子级以获取 DOM 元素
- git - 执行 git lfs 迁移后无法 svn rebase
- android - Maven发布多模块android库
- jenkins - jenkins + sonar + github 集成,没有身份验证令牌
- azure - 部署后如何通过 VSTS 删除 Azure kudu 中的文件
- android - 省电模式后地理围栏未触发
- css - Angular 6 - 更改复选框样式是否被选中
- elasticsearch - 基于聚合结果在 Elasticsearch 中提升分数