我有一个 UserControl,它是一个按钮,具有某些特征,并且我有一个窗口,其中有几个“正常”样式的按钮。在同一个窗口上,我定义了一种样式来覆盖一些正常特征,并且我想要其中的一些(有点像键盘布局)。我拥有的是一个包含 30 行的 UniformGrid,如下所示:
<wft:TouchButton Style="{StaticResource smallButtonStyle}" Click="TouchButton_Click" Tag="1">1</wft:TouchButton>
<wft:TouchButton Style="{StaticResource smallButtonStyle}" Click="TouchButton_Click" Tag="2">2</wft:TouchButton>
<wft:TouchButton Style="{StaticResource smallButtonStyle}" Click="TouchButton_Click" Tag="3">3</wft:TouchButton>
其中,行与行之间唯一变化的是标签和内容值。有什么更好的方法来布局像这样的重复内容,其中样式和单击事件不必出现在每一行上?
更好的方法是在代码中创建一个数据对象来表示您想要在 UI 中出现的 30 个项目,例如:
class DataObject
{
string Tag {get;set;}
string Content {get;set;}
}
(我相信你能想出一个比这更好的名字!)。然后创建 30 个项目并将它们设置为 ItemsControl 的 ItemsSource:
List<DataObject> myObjects = new List<DataObject>();
// populate here
itemsControl.ItemsSource = myObjects
您的 ItemsControl 有一个用于呈现每个项目的 DataTemplate:
<ItemsControl x:Name="itemsControl">
<!-- specify the panel that is the container for your items -->
<ItemsControl.ItemPanelTemplate>
<ItemPanelTemplate>
<UniformGrid/>
</ItemPanelTemplate>
</ItemsControl.ItemPanelTemplate>
<!-- specify the template used to render each item -->
<ItemsControl.ItemTemplate>
<DataTemplate>
<wft:TouchButton Style="{StaticResource smallButtonStyle}"
Click="TouchButton_Click"
Tag="{Binding Tag}"/
Content="{Binding Content}">
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)