WPF 重复元素
我有一个 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>
行与行之间唯一变化的是标签和内容值。有什么更好的方法来布局像这样的重复内容,其中样式和单击事件不必出现在每一行上?
I have a UserControl that is a button, with certain characteristics, and I have a window that has several of these buttons in their "normal" style. On this same window, I have defined a style that overrides some of the normal characteristics, and I want a bunch of them (sort of like a keyboard layout). What I have is a UniformGrid with 30 lines like this:
<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>
where the only thing changing from line to line is the Tag and Content values. What is a better way to lay out something repetitive like this, where the Style and Click events do not have to be on every line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更好的方法是在代码中创建一个数据对象,代表您想要在 UI 中显示的 30 个项目,例如:(
我相信您可以想出一个比这更好的名称!)。然后创建 30 个项目并将它们设置为 ItemsControl 的 ItemsSource:
您的 ItemsControl 有一个用于呈现每个项目的 DataTemplate:
A better way would be to create a data-object in code that represents the 30 items that you want in your UI, for example:
(I am sure you can come up with a better name than that!). Then create your 30 items and set them as the ItemsSource of an ItemsControl:
Your ItemsControl has a DataTemplate that is used to render each item:
我猜想 ColinE 的回答有些离谱,我给了他 +1,因为他为我指明了正确的方向 [谢谢],尽管这并没有完全奏效。我最终得到的结果很接近:
在窗口的构造函数中,设置 30 条几乎相同的行:
然后,这个 xaml(请注意,“Caption”是我们用户控件的属性,因此它不适用于你):
I guessed that ColinE's response was off the top of his head, and I gave him a +1 for pointing me in the right direction [THANKS], although it didn't exactly work. What I ended up with was close:
In the constructor for the window, to set up the 30 almost-identical lines:
Then, this xaml (note that "Caption" is a property of our user control, so it won't work for you):
另一种(更多的是纯 xaml)解决方案是使用基于您命名的样式的默认样式,并为 ClickEvent 添加 EventSetter:
为遇到此答案的其他人提供一个完整的通用示例:
您现有的代码可能如下所示:
您可以将其更改为以下内容:
An alternative (more of a pure xaml) solution would be to use a default style BasedOn your named style, and adding an EventSetter for the ClickEvent:
A complete generic example for anyone else who runs across this answer:
Your existing code might look like this:
And you can change it to the following: