在接下来的几天里,我将开始一个相当大的项目,我在思考什么是创建这个项目的最佳方式。现在我有一个关于控件的重要问题,我真的不知道实现它的最佳方式是什么。
我有一个led灯矩阵。(32x16 leds)。这些必须在网格中显示,现在棘手的部分。我必须能够和他们一起做很多事情。例如,我必须能够很容易地访问数据绑定leds,执行一些操作,比如将它们全部向右或向左移动2次,或者将它们反转,等等。
我考虑将它们显示在一个项目控件中,如下所示:
<ItemsControl ItemsSource="{Binding Path=Leds}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="16" Columns="32"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:Led}">
<Ellipse Name="ellipse" Fill="Green"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=State}" Value="Off">
<Setter TargetName="ellipse" Property="Fill" Value="Red"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>但是我应该如何处理led上的鼠标点击来打开它或关闭它。(我正在使用MVVM),您将如何在leds中抽象整个网格?
有很多解决方案,但我不知道该采用哪一个?
希望你有一个有趣的想法,如何创建一个简单而干净的解决方案。
发布于 2012-08-09 21:33:46
与其使用UniformGrid,不如建议您使用in this stackoverflow thread引入的优秀的DataGrid2D控件
它允许您将DataGrid2D的ItemsSource绑定到2D对象,在本例中为Led[,],然后将在2D数组中显示您所做的任何更改。
发布于 2012-08-09 21:37:07
考虑在ItemsControl中使用常规的Grid,并将ItemContainerStyle中的Grid.Column和Grid.Row绑定到对象上的值,而不是使用ItemsControl。这将使移位整列或整行等操作变得容易得多。
您可以编写16和32行/列定义,或者我提供了一些attached properties on my blog,让您只需一行即可完成此操作。
<ItemsControl ItemsSource="{Binding Leds}">
<!-- ItemsPanelTemplate -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid local:GridHelpers.RowCount="16"
local:GridHelpers.ColumnCount="32" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<!-- ItemContainerStyle -->
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Grid.Column"
Value="{Binding ColumnIndex}" />
<Setter Property="Grid.Row"
Value="{Binding RowIndex}" />
</Style>
</ItemsControl.ItemContainerStyle>
<!-- ItemTemplate -->
<ItemsControl.ItemTemplate>
<DataTemplate>
...
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>至于单击它们来打开/关闭它们,请将每个项目包装在Button标记中,并覆盖Template以使其看起来符合您的要求。然后,您可以将Command事件绑定到ViewModel中的属性,并将它作为CommandParameter传递给选定的发光二极管
<Button Command="{Binding RelativeSource={RelativeSource ItemsControl}, Path=DataContext.ToggleLedCommand}"
CommandParameter="{Binding }">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Ellipse Name="ellipse" Fill="Green"/>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding Path=State}" Value="Off">
<Setter TargetName="ellipse" Property="Fill" Value="Red"/>
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>而您的Command实现将简单地
void ToggleLed(LedModel led)
{
led.State = (led.State == "On" ? "Off" : "On");
}https://stackoverflow.com/questions/11884373
复制相似问题