Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I edit immutable objects in WPF without duplicating code?
    text
    copied!<p>We have lots of immutable value objects in our domain model, one example of this is a position, defined by a latitude, longitude &amp; height.</p> <pre><code>/// &lt;remarks&gt;When I grow up I want to be an F# record.&lt;/remarks&gt; public class Position { public double Latitude { get; private set; } // snip public Position(double latitude, double longitude, double height) { Latitude = latitude; // snip } } </code></pre> <p>The obvious way to allow editing of a position is to build a ViewModel which has getters <em>and</em> setters, as well as a ToPosition() method to extract the validated immutable position instance. While this solution would be ok, it would result in a lot of duplicated code, especially XAML.</p> <p>The value objects in question consist of between three and five properties which are usually some variant of X, Y, Z &amp; some auxiliary stuff. Given this, I had considered creating three ViewModels to handle the various possibilities, where each ViewModel would need to expose properties for the value of each property as well as a description to display for each label (eg. "Latitude").</p> <p>Going further, it seems like I could simplify it to one general ViewModel that can deal with N properties and hook everything up using reflection. Something like a property grid, but for immutable objects. One issue with a property grid is that I want to be able to change the look so I can have labels and textboxes such as:</p> <pre><code>Latitude: [ 32 ] &lt;- TextBox Longitude: [ 115 ] Height: [ 12 ] </code></pre> <p>Or put it in a DataGrid such as:</p> <pre><code>Latitude | Longitude | Height 32 115 12 </code></pre> <p><em>So my question is:</em></p> <p>Can you think of an elegant way to solve this problem? Are there any libraries that do this or articles about something similar?</p> <p>I'm mainly looking for:</p> <ul> <li>Code duplication to be minimized</li> <li>Easy to add new value object types</li> <li>Possible to extend with some kind of validation</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload