views:

291

answers:

2

I have two custom controls that are analogous to a node and the control that draws links between nodes.

I would like to have both controls written as much in xaml as possible. The link stores both nodes as dependency properties, and I use databinding to move the line between the nodes whenever the nodes move.

It would be great to be able to change some other value of the line, for instance the stroke width, depending on the distance between the two nodes. So the property needs to update when either node moves, and I can't quite get my head around how that would work.

Anyone got any ideas?

A: 

You could define a property StrokeWidth in your link class that gets calculated every time the nodes move and then bind the appropriate style property to it.

I suppose you could also try to do something with DataTriggers, but they need specific values to work with - you can't use any kind of expressions. This would make it difficult to have the solution scale well to a wide array of distances between the nodes.

17 of 26
I currently use a property in the code-behind and databind to it in the xaml. When either node moves they tell any links to update. Despite being inexperienced with WPF, it just doesn't feel like the most elegant solution.
tenpn
+1  A: 

you can try doing something like that:

  1. as in previous post define a width, stroke (whatever you need) property on your link class
  2. define a multibinding applied to that property, passing your two nodes to the binding it should look like:

<Multibinding Converter="{StaticResource converter}">
<Binding Path="Node1" RelativeSource|Source.../>
<Binding Path="Node2" ... />
</Multibinding>

  1. Implement interface IMultiValueConverter, which will basically calculate how the stroke should look like based on the distance between nodes.

  2. in xaml create instance of your converter, and add it to your multibinding's Converter property.

the advantage of this solution is, that you have pretty clear class model and each class does simple tasks. moreover, later on, you can configure your converter class to support extra cases without touching node class which stays simple and is designed simply for displaying nodes.

in general, whenever you have to map multiple property values to one other property, you'll have to use multibinding and converter.

Greg