开发者

Silverlight: Apply effect on all items that match some criteria in an ItemsControl

I'm loading images dynamically onto a Canvas based on some data I receive from the back end. I have a data structure that looks like this:

ID: 1  GROUP: A  X: 10  Y: 10
ID: 2  GROUP: A  X: 20  Y: 20
ID: 3  GROUP: A  X: 30  Y: 30
ID: 4  GROUP: B  X: 40  Y: 40
ID: 5  GROUP: B  X: 50  Y: 50
ID: 6  GROUP: C  X: 60  Y: 60

I'm loading this data into an ItemsControl that looks something like this:

<ItemsControl ItemsSource="{Binding MyDataSet}">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Canvas>
        <Image Height="10" Width="10" 
               Source="/someImage.png" 
               Canvas.Left="{Binding X}" 
               Canvas.Top="{Binding Y}" 
               MouseEnter="Image_MouseEnter"
               MouseLeave="Image_MouseLeave" />
      </Canvas>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>

The images are showing up on the Canvas just fine. When the user places their mouse over an image, the Image_MouseEnter event handler replaces the image with another "highlighted" image. The Image_MouseLeave method swaps the images back. This is also working fine.

What I want to do is also use the "highlighted" image for each other image that has the same GROUP as the image开发者_如何转开发 has hovered over. So if I place my mouse over the image for ID: 1 GROUP: A, it should swap out the images for IDs 2 and 3.

Just to make things more interesting, I'm also using MVVM. :)

Any suggestions?


This sounds pretty straightforward to me. I would do the following:

  1. Wrap each of of your data items in a view-model, DataItemViewModel. And place them within an ObservableCollection.
  2. Create a relationship between DataItemViewModel and the collection that holds them, so that you can navigate from the child to the parent.
  3. Bind the Image.Source property to the DataItemViewModel. You will need this so that you can swap the source when the image is highlighted.
  4. Handle your mouse enter / leave events in code-behind (yes, this is allowed in MVVM!).
  5. On mouse-enter, change the DataItemViewModel state to highlighted (perhaps expose a boolean IsHighlighted property), and use this to change the image source. Also, navigate back to the parent collection so that you can find all other DataItemViewModel instances that mach your criteria and set their highlighted state to true as well.

Hope that help!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜