|
Actually, my response was 100% correct given the information the poster gave. Whether he said it was an example or not is irrelevant. He did not indicate that code involved was not his or off limits. Had he responded to my response with that fact, I may have provided a different answer.
For now, I will stand by my response that separating the data layer into a POCO and a M just for the sake of doing so (thinking it is a good separation of duty) is completely un-necessary and completely over-engineered and it would have completely solved his problem of converting between a Day and a DayModel.
Just as I will stand by my other response (that you also down voted) that the use of partial classes is completely proper. If you hate partial classes, well, you better go and explain yourself to Bill Gates (er, Steve Balmer) because pretty much ALL his technologies use them. Winforms, WPF, WCF, ADO.NET, etc.
EDIT: BTW, I gave your post a 3 (should have probably gone lower though) because it was an abuse of technology given the scenario. Use of factories and DI for such a simple problem? Really? Why not go even further and use a remote https server behind a firewall using 512 bit encryption and a separate validation server to ensure the object is valid?
|
|
|
|
|
Collin Jasnoch wrote: Your respnoce was simply a "You shouldn't do that." Nothing more nothing less.
No explanation other than the claim of over engineering.
Actually, my response was that they should be the same object and not two different ones which would solve the OPs problem. Given the info the OP posted, this was the correct answer.
Collin Jasnoch wrote: So, how are you going to handle a 3rd party controlled model? Or an object that
you control that is used elsewhere and has embedded objects of which are not
INOC? You make the assumption that the developer controls all aspects. In
reality most patterns (Including MVVM) are created because we can not control
all components. For the few, hey great. Code how you want. For the rest of the
world we follow the patterns for easy transition, upgrades, extensions, testing
etc. etc. etc
Who asked about 3rd party components? Certainly not the OP. Quit making up imaginary scenarios to justify your answer. Until the OP says that he is using 3rd party components that are not designed for MVVM, your point is completely irrelevant to the OPs question.
Where do you get off saying I don't follow design patterns? I certainly do. I don't spend a month implementing a design pattern when a 5 minute "shortcut" will work "for now". I certainly don't write all my code using "shortcuts" or I wouldn't even use MVVM.
Collin Jasnoch wrote: I doubt you have actually implimented a large scale MVVM project. The poster
asked what is the common way to deal with that scenerio (you may want to go back
and look... cause again you did not answer his question. You said he is over
engineering).
Where do you get off saying what I have implemented or not? I'm actually working on a large scale MVVM project right now and yes, I am using 100% proper MVVM with DI, messenger to communicate between views, etc. I use technologies where appropriate. Not to feed my ego like you obviously do.
Collin Jasnoch wrote: You stating it is an abuse of technology is like stating OOP should not be used
in simple apps. If you don't understand that, then it is likely you really don't
understand what DI is.
Lol... you need help bro. Go see a therapist. I certainly know what DI is. In fact, I have personally implemented a DI container. Have you?
Collin Jasnoch wrote: First off, your claim here is insane. Do you really think Gates or Balmer
invented those platforms??? Secondly they use them only in 'AUTO GENERATED
CODE'. The purpose is quite obvious (well atleast to most I guess). If I have
some auto generated code that resides in the same file as that which the
developer is modifying I have a high risk of the developer modifying code that
will be overritten when 'AUTO GENERATED' again. Or it is possible the developer
simple breaks the logic because they do not fully understand the logic flow or
meaning of the code. This was why partial classes were created and this is WHEN
they should be used. Not because you want to EXTEND a class. In fact, there is a
thing called Extensions[^]. In any other case you should be refactoring and
making new objects.
Your mental issues are coming out again. Did I ever claim Gates or Balmer invented WPF? I said that Microsoft uses partial classes everywhere. I'll certainly listen to Microsoft and follow their advice before I listen to you and your insane rants.
Who ever said anything about modifying auto-generated classes? Thats dumb.
Seems like Microsoft disagrees with you, yet again... here... I'll post the link for you so you can read up on partial classes:
http://msdn.microsoft.com/en-us/library/wa80x488.aspx[^]
|
|
|
|
|
Collin Jasnoch wrote: I did not vote on any of your 'Partial Class' posts. I will inform you I voted
for you comment on IValueConvertor
SledgeHammer01 wrote:
In MVVM, IValueConverter and IMultiValueConverter
are very rarely used because the VM does that work.
That is because that statement is completely false. Maybe in your
applications you have programmed this way, but a small search on google will
show you they deffinately have their place.
Do you not understand the difference between "rarely" and "never".
You should actually read the latest response from the OP in which he clearly states that all your imaginary doom scenarios are not at play, so following your own "don't mislead the OP" rule, I have to down vote you.
|
|
|
|
|
Thank you guys for all replies. No need to argue, really. To clarify a few points: the project which inspired the question is certainly more complex than counting days in a week (it is actually sports related but I came with the example to spare myself the need to explain the particular sport). It is a non commercial activity of mine and I though that one of the benefits would be to get comfortable with the celebrated MVVM. That is why I overthink things, because in this rare case I can afford it, and I can hardly get a thorough understanding by underthinking.
SledgeHammer's reaction was my reasoning exactly - why complicate things with unneccessary model objects when viewmodel alone does all I need with no further complications. But most design patterns have use for model classes, so I thought there must be a "proper" (whatever it means) way to desing the application with model and viewmodel separated. I'll look into factory classes, thanks for the suggestion.
I never said there is 1:1 correspondence between model and viewmodel classes, on the contrary.
I remember now what made me think about the design the way I described. In one article on MVVM (don't know which one, maybe I read too many) someone said that model classes should contain only data that need to be stored in the data store. In particular, data which can be computed should not be present in the model classes but rather in the viewmodel.
Back to my example - if the Day class contains a DateTime information about the time some employee came to work and another DateTime info when the employee left, it is all you need to store. Then my view wants to show how many hours the employee spend working, which can be computed from the data but it is job (I believe/ed) of the DayViewModel to provide this information. That is why I thought I needed both Day and DayViewModel. I got the impression that model classes store data, viewmodel contains all logic and view deals with appearance.
I don't seek perfect code for the sake of it but I can hardly appreciate the benefits of MVVM for large scale applications if I can't successfully use it (with a bit of overkill) even for a small application.
I'll be happy to hear any other suggestions and advice, H.
|
|
|
|
|
I never said you shouldn't use MVVM. On the contrary, I think its great even for small apps once you have a good MVVM framework established. I just said you shouldn't separate the data layer from the model. I'll even toss Colin a bone here and add "unless there is a very good reason to do so". It doesn't seem that you are using any 3rd party components and it seems like you are owning all the code, so there is no reason to do so.
I also never said anything about combining the model and viewmodel. Those should definitely be separate.
The model should implement INPC (or derive from a base class that does) and should handle dealing with the data. I.e. writing to the database, or XML, etc.
The viewmodel should well, I hate to use the word "repackage" because that might give you the impression that you are supposed to repackage the data, which you aren't. Its just a "gateway" from the model to the view. It just presents the data in a way the view can use it. Often times, this is just exposing a collection as a property to get the data to the view. It really doesn't have to be all that complicated. With a few exceptions, most of the VMs I've seen in my life are very simple which is one of the joys of MVVM IMO. If the VM is doing a ton of work in manipulating the data, something is wrong somewhere. The VM also exposes commands that the View can use to manipulate the model, but its just a hook up. The real work of manipulating the models internals belong in the model.
|
|
|
|
|
I am starting to get it now. As I explained, I lived under the impression that model classes should only store data and not contain any means to manipulate them (this belongs to viewmodel). I learned this in some MVVM article, possibly not very good one because you say the direct opposite.
Still it is good to know there are ways to deal with data sources I do not have under my control, so I appreciate Colin's input.
But suppose the UI allows for direct manipulation with the individual Day objects (which are low in the whatever-Week-Day hierarchy). I could implement this by exposing a Manipulate (or something) command in the Day class, but rather in the DayViewModel class, since command handling is the viewmodel's job, right? If so, I am back to square one since I need the Day model class which manipulates the data and the DayViewModel which exposes the manipulation commands. If this is correct that the question still stands, how can the Week model class contain a collection of Day objects if it actually needs DayViewModel objects and thus would have to be tied with one particular viewmodel? If you say to expose the commands directly in the Day class, then I really see no point of VM layer since it would do nothing of any value.
|
|
|
|
|
I have a datagrid and I want to put comboboxes for filtering for each of the columns above the respective columns. I would like the combobox widths to track the width of the specific column they are filtering. I am trying to bind the combobox width to the actual width of the datagrid column but it doesn't seem to work. What am I doing wrong?
Thanks,
Preston
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ComboBox Width="{Binding FirstColumn.ActualWidth}"></ComboBox>
<DataGrid Grid.Row="1">
<DataGrid.Columns>
<DataGridTextColumn x:Name="FirstColumn"
MinWidth="180"
Header="First Column"></DataGridTextColumn>
<DataGridTextColumn x:Name="SecondColumn"
MinWidth="180"
Header="Second Column"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
|
|
|
|
|
Thanks Collin, that worked great for setting the width but now I need to make the location line up with the start of the datagrid column. How can I do that? I don't see a property that I can bind to for that purpose.
I think I have figured out how to do that. If I just wrap the comboboxes in a horizontal wrap panel that does the trick. Thanks again for the help.
modified 13-Oct-11 17:13pm.
|
|
|
|
|
It looks like I may have spoken too soon. Binding my comboboxes to the ActualWidth of the dataGrid columns they should be above works great until I try to change the size of the app from full screen. Then I get DependencyProperty.UnsetValue is not a valid value for property 'Background' error.
I commented out the comboboxes and thought it had fixed the problem but once I grabbed the corner of the non maximized app and resized it gave the error again. So I guess it has something to do with my dataGrid.
Update: I found that the problem was in the one of the styles on the datagrid. Problem solved.
Thanks,
Preston
modified 14-Oct-11 16:03pm.
|
|
|
|
|
I am creating a WPF ComboBox for a WPF Windows application dynamically. However, when I build a list of a class object with 2 items in the list and bind to the combobox, I see records in the combobox but do not see any text displayed. I am setting the DisplayMemberPath appropriately I think. Any ideas?
Class AnswerChoice
Public AnswerChoiceID As Integer
Public AnswerChoice As String
End Class
Private Function GetAnswerChoices() As List(Of AnswerChoice)
Dim lstAnswerChoices As New List(Of AnswerChoice)
Dim objAnswerChoice As AnswerChoice
objAnswerChoice = New AnswerChoice
objAnswerChoice.AnswerChoiceID = 1
objAnswerChoice.AnswerChoice = "Answer Choice One"
lstAnswerChoices.Add(objAnswerChoice)
objAnswerChoice = New AnswerChoice
objAnswerChoice.AnswerChoiceID = 2
objAnswerChoice.AnswerChoice = "Answer Choice Two"
lstAnswerChoices.Add(objAnswerChoice)
Return lstAnswerChoices
End Function
Dim ctrlComboBox As New ComboBox()
ctrlComboBox.Width = 300
ctrlComboBox.HorizontalAlignment = Windows.HorizontalAlignment.Left
ctrlComboBox.Name = "cboBox"
ctrlComboBox.ItemsSource = GetAnswerChoices()
ctrlComboBox.DisplayMemberPath = "AnswerChoice"
ctrlComboBox.SelectedValuePath = "AnswerChoiceID"
|
|
|
|
|
You need to make your fields in Class AnswerChoice Properties like this
Dim intAnswerChoiceID As Integer
Public Property AnswerChoiceID As Integer
Get
Return intAnswerChoiceID
End Get
Set(ByVal value As Integer)
intAnswerChoiceID = value
End Set
End Property
Dim strAnswerChoice As String
Public Property AnswerChoice As String
Get
Return strAnswerChoice
End Get
Set(ByVal value As String)
strAnswerChoice = value
End Set
End Property
My advice also would be to use an ObservableCollection rather than a List to store your collection, as it notifies your UI if there are any changes to the collection.
Hope this helps
When I was a coder, we worked on algorithms. Today, we memorize APIs for countless libraries — those libraries have the algorithms - Eric Allman
|
|
|
|
|
|
I used this same technique with a Tree View control it works really well.
|
|
|
|
|
It's always much better to work with Properties rather than public fields, as that way the field can only be updated internally in the class declaring them.
When I was a coder, we worked on algorithms. Today, we memorize APIs for countless libraries — those libraries have the algorithms - Eric Allman
|
|
|
|
|
I have a datagrid with checkboxes to select a level of permissions for a user and a text field to display the current level. I have subscribed to the SelectedItemChanged event of the datagrid to do the logic required to update my text field. But the property bound to the checkbox just checked has not been set true when my handler is called. Is there some other event I should use or something I can do so that the change is applied to the bound property when I evaluate things?
I have the binding mode set to TwoWay and the UpdateTrigger to PropertyChanged in the xaml.
Thanks,
Preston
|
|
|
|
|
Could you post the XAML for the DataGrid, and also let us know whether your classes implement INotifyPropertyChanged .?
When I was a coder, we worked on algorithms. Today, we memorize APIs for countless libraries — those libraries have the algorithms - Eric Allman
|
|
|
|
|
The class the collection is based on does implement INotifyPropertyChanged. Here's the grid XAML.
<DataGrid ItemsSource="{Binding CurrentBoxEmployeePermissions}"
x:Name="BoxesPageEmployeesGrid"
AutoGenerateColumns="False" SelectionMode="Extended"
Style="{DynamicResource MyDataGridStyle}"
ColumnHeaderStyle="{StaticResource GridHeaderStyle}"
IsSynchronizedWithCurrentItem="True"
ColumnWidth="SizeToCells"
CanUserResizeRows="False"
SelectionChanged="OnReevaluateAppliedBoxParameters">
<DataGrid.Columns>
<DataGridTextColumn x:Name="ColumnEmployeeName"
Header="Employee Name"
Binding="{Binding EmployeeName}"
Width="Auto"
MinWidth="180"
IsReadOnly="True">
<DataGridTextColumn.ElementStyle>
<Style>
<Setter Property="TextBlock.FontSize"
Value="16" />
<Setter Property="TextBlock.FontWeight"
Value="Bold" />
<Setter Property="TextBlock.TextAlignment"
Value="Center" />
<Setter Property="TextBlock.VerticalAlignment"
Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<ATC_Admin:AutoCommitCheckBoxColumn Header="System User"
ElementStyle="{StaticResource CheckBoxStyle}"
EditingElementStyle="{StaticResource CheckBoxStyle}"
Width="Auto"
Binding="{Binding SystemUser, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></ATC_Admin:AutoCommitCheckBoxColumn>
<ATC_Admin:AutoCommitCheckBoxColumn Header="Maintenance"
ElementStyle="{StaticResource CheckBoxStyle}"
EditingElementStyle="{StaticResource CheckBoxStyle}"
Width="Auto"
Binding="{Binding Maintenance, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></ATC_Admin:AutoCommitCheckBoxColumn>
<ATC_Admin:AutoCommitCheckBoxColumn Header="Administrator"
ElementStyle="{StaticResource CheckBoxStyle}"
EditingElementStyle="{StaticResource CheckBoxStyle}"
Width="Auto"
Binding="{Binding Administrator, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></ATC_Admin:AutoCommitCheckBoxColumn>
<DataGridTextColumn Header="Applied Permission"
Binding="{Binding AppliedPermission}"
Width="Auto"
MinWidth="180"
IsReadOnly="True">
<DataGridTextColumn.ElementStyle>
<Style>
<Setter Property="TextBlock.FontSize"
Value="16" />
<Setter Property="TextBlock.FontWeight"
Value="Bold" />
<Setter Property="TextBlock.TextAlignment"
Value="Center" />
<Setter Property="TextBlock.VerticalAlignment"
Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
|
|
|
|
|
The collection the datagrid is bound to is an observable collection of this object.
public class BoxEmployeePermissions : INotifyPropertyChanged
{
private AdminMediator mMediator;
public BoxEmployeePermissions(AdminMediator mediator)
{
mMediator = mediator;
}
/// <summary>
/// Name of the Employee.
/// </summary>
public string EmployeeName
{
get { return mEmployeeName; }
set
{
mEmployeeName = value;
OnPropertyChanged("EmployeeName");
}
}
private string mEmployeeName;
/// <summary>
/// Employee's unique ID.
/// </summary>
public int EmployeeId
{
get { return mEmployeeId; }
set
{
mEmployeeId = value;
OnPropertyChanged("EmployeeId");
}
}
private int mEmployeeId;
/// <summary>
/// Basic system user for this box.
/// </summary>
public bool SystemUser
{
get { return mSystemUser; }
set
{
mSystemUser = value;
if (value)
{
Maintenance = false;
Administrator = false;
}
OnPropertyChanged("SystemUser");
mMediator.BoxEventAggregator.GetEvent<ReevaluateAppliedBoxParameters>().Publish(new object());
}
}
private bool mSystemUser;
/// <summary>
/// Maintenance level access to the box.
/// </summary>
public bool Maintenance
{
get { return mMaintenance; }
set
{
mMaintenance = value;
if (value)
{
SystemUser = false;
Administrator = false;
}
OnPropertyChanged("Maintenance");
mMediator.BoxEventAggregator.GetEvent<ReevaluateAppliedBoxParameters>().Publish(new object());
}
}
private bool mMaintenance;
/// <summary>
/// Administrator level access to the box.
/// </summary>
public bool Administrator
{
get { return mAdministrator; }
set
{
mAdministrator = value;
if (value)
{
SystemUser = false;
Maintenance = false;
}
OnPropertyChanged("Administrator");
mMediator.BoxEventAggregator.GetEvent<ReevaluateAppliedBoxParameters>().Publish(new object());
}
}
private bool mAdministrator;
...
And things do update eventually. It just takes leaving the row with the checkbox in it and sometimes coming back to that row and leaving again before the update occurs.
|
|
|
|
|
I'm not sure how I would do that. I need to do a fair amount of evaluating things when one of those checkboxes is clicked. And I need the values of the properties to be up to date when I do that evaluation. Clearly the property attached to the checkbox has not been updated yet when the selectedItemChanged event is fired but I have yet to come up with an event I could use instead or a way to force the update of the property. I've been struggling with this for over a day now. Very frustrating for something that seems like it just oughta work.
|
|
|
|
|
IValueConverter and IMultiValueConverter are pretty convenient when it comes to value conversions in a software but, as we all know, there is never one way to do things.
The below scenario is very simple: a Model exposes properties to a ViewModel and these values need to be presented in the View.When these values need to be displayed in a specific way - say, the dimensions of an image diplayed with the appropriate units in a status bar - the above interfaces would do the job. However...
Some one said once that a ViewModel is simply "a converter in steroids" and he seems to have a point. The ViewModel could do the conversions via some simple routines and expose the results to the view for binding. This way we avoid loading our application with classes that - most probably - will be used only once. On the other hand, we bulk the ViewModel with lines and lines of code, loosing the focus and reducing maintainability.
What do you think? Which, in your opinion, is the best practice? I would really like to hear your opinions on the matter!
|
|
|
|
|
If you are very concerned about performance(or lots of data needs to be loaded) in the view, you can do the conversion in the view model.
If your view does not require too much data to be loaded, a converter can be used. It decouples the UI from the view model even further making the entire decoupling neater.
Just my view!
|
|
|
|
|
In MVVM, IValueConverter and IMultiValueConverter are very rarely used because the VM does that work.
|
|
|
|
|
This is exactly what I'm talking about! But...is it really preferable to end up with a hefty ViewModel as opposed to a few more classes?
|
|
|
|
|
If you are finding that your VM is doing too much repackaging, its likely a deficiency in your model . One thing that I like to do is make the model a partial class, so it can be easily extended in the UI without value converters or adding a ton of repacking in the VM. You'll find that a lot of stuff from Microsoft does exactly this. ADO.NET and WCF all make the models partial.
|
|
|
|
|
It really depends what you're trying to do. If it's purely acting on the VM to do something visual, I'd use a converter. If it was a deriving a new value for display from a current one, I'd rather do it in the VM. So, what do I mean by doing something visual? Well, in one application we wrote, we had to format the display to act like a typical accounts system and display negative numbers in red. In this case, adding the red brush in the VM was not one we felt comfortable with; using an instance of IValueConverter was a much better choice for us.
|
|
|
|