【问题标题】:PutCheckBoxes or Images into UniformGrid将CheckBoxes 或图像放入UniformGrid
【发布时间】:2012-06-14 21:28:36
【问题描述】:

我尝试在 WPF 中实现Whac a mole game

Molehills 位于 UniformGrid 中。根据选项,鼹鼠山是复选框或图像。麻烦来了。

我不知道如何实现 UniformGrid 以同时接受 checkboxesimages
也许您对我如何解决它有更好的想法。也许 UniformGrid 用于复选框和图像不是一个好主意。

我是这样尝试的:

<ItemsControl Name="GameBlocksItemsControl" ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=Moles}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}, Path=Conf.Cols}" 
                            Rows="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}, Path=Conf.Rows}" 
                            Name="MolesGrid">
            </UniformGrid>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

MolesObject 的集合,因此我可以将 CheckboxBitmapImage 放在那里。

不幸的是,在将一些 BitmapImage 添加到集合后,它们无法正确显示(而不是图像,其中写入:System.Windows.Media.Imaging.BitmapImage)。如果我将 CheckBoxes 添加到集合中,它们会显示得很好。

我考虑过编写转换器,但这样的转换器必须知道指定的 ObjectCheckBox 还是 BitmapImage。即使可以编码,也不是很优雅的解决方案

【问题讨论】:

    标签: c# wpf universal uniformgrid


    【解决方案1】:

    我个人会根据SelectedViewOption 简单地设置ItemTemplate

    例如,为简单起见,假设SelectedViewOption 是一个字符串:

    <Style x:Key="MyItemsControlStyle" TargetType="{x:Type ItemsControl}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding SelectedViewOption}" Value="Image">
                <Setter Property="ItemTemplate" Value="{StaticResource ImageTemplate}" />
            </DataTrigger>
            <DataTrigger Binding="{Binding SelectedViewOption}" Value="CheckBox">
                <Setter Property="ItemTemplate" Value="{StaticResource CheckBoxTemplate}" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
    

    这不仅可以让您在以后轻松添加其他视图选项,还可以从您的DataContext 中删除任何特定于视图的代码,例如CheckBoxesImages。通常,您希望您的 UI 和业务逻辑层分开,这允许您这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      相关资源
      最近更新 更多