WPF重复元素

Kel*_*ine 5 wpf wpf-controls

我有一个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>
Run Code Online (Sandbox Code Playgroud)

其中唯一不变的是标记和内容值.什么是更好的方式来布置像这样重复的东西,其中Style和Click事件不必在每一行?

Col*_*inE 9

更好的方法是在代码中创建一个数据对象,代表您在UI中需要的30个项目,例如:

class DataObject
{
  string Tag {get;set;}
  string Content {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

(我相信你能想出一个比这更好的名字!).然后创建30个项目并将它们设置为ItemsControl的ItemsSource:

List<DataObject> myObjects = new List<DataObject>();
// populate here
itemsControl.ItemsSource = myObjects
Run Code Online (Sandbox Code Playgroud)

您的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>
Run Code Online (Sandbox Code Playgroud)


Kel*_*ine 4

我猜想 ColinE 的回答有些离谱,我给了他 +1,因为他为我指明了正确的方向 [谢谢],尽管这并没有完全奏效。我最终得到的结果很接近:

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

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

然后,这个 xaml(请注意,“Caption”是我们用户控件的属性,因此它对您不起作用):

<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>
Run Code Online (Sandbox Code Playgroud)