WPF 重复元素 [英] WPF repeating elements

查看:36
本文介绍了WPF 重复元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UserControl,它是一个按钮,具有某些特征,并且我有一个窗口,其中有几个正常"样式的按钮.在同一个窗口中,我定义了一个覆盖一些正常特征的样式,我想要一堆它们(有点像键盘布局).我拥有的是一个像这样有 30 行的 UniformGrid:

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>

从一行到另一行唯一改变的是标签和内容值.有什么更好的方法来布置类似这样的重复内容,其中 Style 和 Click 事件不必在每一行?

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?

推荐答案

我猜想 ColinE 的回应超出了他的头脑,我给了他 +1 给他指出了正确的方向 [THANKS],尽管它没有完全奏效.我最终得到的结果很接近:

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:

在窗口的构造函数中,设置 30 行几乎相同的行:

In the constructor for the window, to set up the 30 almost-identical lines:

var numberButtons = Enumerable.Range( 1, 30 )
    .Select( r => new KeyValuePair<string,string>( r.ToString( ), r.ToString( ) ) )
    .ToList( );
numberButtonItems.ItemsSource = numberButtons;

那么,这个xaml(注意Caption"是我们用户控件的一个属性,所以它对你不起作用):

Then, this xaml (note that "Caption" is a property of our user control, so it won't work for you):

<ItemsControl Grid.Row="1" x:Name="numberButtonItems">
    <ItemsControl.ItemsPanel>
    <!-- specify the panel that is the container for your items -->
        <ItemsPanelTemplate>
             <UniformGrid Rows="4" Columns="10" HorizontalAlignment="Left" />
        </ItemsPanelTemplate>
   </ItemsControl.ItemsPanel>
   <!-- specify the template used to render each item -->
   <ItemsControl.ItemTemplate>
        <DataTemplate>
             <wft:TouchButton Style="{StaticResource smallButtonStyle}"
                  Click="TouchButton_Click"
                  Tag="{Binding Key}"
                  Caption="{Binding Value}"/>
        </DataTemplate>
   </ItemsControl.ItemTemplate>
 </ItemsControl>

这篇关于WPF 重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆