如何在WPF中以漂亮的图块格式显示动态数量的对象?

ila*_*sch 2 c# wpf

我想制作可以显示1或2个视频的应用程序.

在窗口的左侧,将有2个标记为"1"或"2"的按钮作为我想在应用程序右侧显示的图块数量.

点击"1",视频将在整个右侧播放.
点击"2",右侧将显示2个视频,共2个视频.

现在它唯一的全窗口显示1个视频,另一个将整个窗口拆分为2并显示2个视频,但如果我想要4个视频,我想将主窗口拆分为4并显示4个不同的视频.

实现这个的最佳方法是什么?

谢谢!

Rac*_*hel 5

根据你在评论中所说的内容,听起来你想要按钮来创建动态数量的视频并让它们在网格中很好地显示

我首先ObservableCollection<VideoPlayer>在您的DataContext中创建一个包含所需视频数量的数据,然后在第二个属性中包含平方根VideoPlayerCollection.Count,向上舍入,以确定网格大小.

然后我会显示VideoPlayerCollection使用ItemsControl它的ItemsPanelTemplate设置为a UniformGrid或者Grid,它将行计数和列数绑定到您的GridSize属性.

(您可能需要构建一些AttachedProperties用于绑定这些属性,因为Grid没有行/列计数属性,我不记得是否可以绑定UniformGrid RowsColumns属性DependencyProperties.我有一些示例如果您对示例感兴趣,可以在此处绑定Grid'sRowCount和ColumnCount的AttachedProperties )

最后,您的按钮会修改您VideoPlayerCollection添加或删除任意数量的项目.

所以你的最终XAML可能看起来像这样:

<DockPanel>

    <StackPanel DockPanel.Dock="Left">
        <Button Content="One Window" 
                Command="{Binding ModifyVideoCountCommand}"
                CommandParameter="1" />
        <Button Content="Two Windows" 
                Command="{Binding ModifyVideoCountCommand}"
                CommandParameter="2" />
        <Button Content="Four Windows" 
                Command="{Binding ModifyVideoCountCommand}"
                CommandParameter="4" />
    </StackPanel>

    <ItemsControl ItemsSource="{Binding VideoPlayerCollection}"
                  ItemTemplate="{StaticResource VideoPlayerTemplate}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Rows="{Binding GridSize}" Columns="{Binding GridSize}" />
            </ItemsPanelTemplate>
        </ItemsPanelTemplate>
    </ItemsControl>

</DockPanel>
Run Code Online (Sandbox Code Playgroud)

虽然DataContext您的表单背后将包含以下属性:

ICommand ModifyVideoCountCommand { get; set; }
ObservableCollection<VideoPlayer> VideoPlayerCollection { get; set; }
int GridSize 
{
    get
    {
        return Math.Ceiling(Math.Sqrt(VideoPlayerCollection.Count));
    }
}
Run Code Online (Sandbox Code Playgroud)

根据您是否使用Grid,您可能还需要为类添加RowIndexColumnIndex属性,VideoPlayer以指定应放置哪个Grid.RowGrid.Column每个VideoPlayer.

<ItemsControl.ItemContainerStyle>
    <Style>
        <Setter Property="Grid.Column" 
                Value="{Binding ColumnIndex}" />
        <Setter Property="Grid.Row" 
                Value="{Binding RowIndex}" />
    </Style>
</ItemsControl.ItemContainerStyle>
Run Code Online (Sandbox Code Playgroud)