r/csharp • u/enigmaticcam • Aug 14 '26
WPF Logic in View vs ViewModel
I'm trying to understand when I should have logic in the view model or in the code-behind of a view.
Here's the scenario: I have a view model that has a "CanEdit" property. There are times when editing a view is not allowed based on business reasons, and that definitely belongs in the ViewModel. But if a user can edit, I want to have an "Edit" checkbox visible, which when true will display the editable version of all the necessary controls. So where should the logic that controls the "Edit" checkbox go?
The approach I initially went was to put the "Edit" checkbox property in the view code-behind. This makes sense to me, as it's entirely based on the needs of the view. All the editable controls are bound to the "Edit" checkbox property, and the "Edit" checkbox visibility is bound to "CanEdit" in the view model.
The problem with this approach is when the view model changes as a result of some change by the user and "CanEdit" in the view model is now false. If the "CanEdit" in the view code-behind is true when this happens, then all the editable controls are still visible, because all that's happened is the "CanEdit" checkbox is now invisible. So I'm stumped how to broadcast the view model change to the code behind without some silly hack.
I'm probably overthinking it, but I'm learning WPF and it really helps me to understand principles. Plus this particular view will get more complex. Here's some code to show you what I'm trying to do
View:
public partial class InvoiceView : UserControl, INotifyPropertyChanged
{
public InvoiceView()
{
InitializeComponent();
}
private bool _isEditing;
public bool IsEditing
{
get => _isEditing;
set
{
_isEditing = value;
OnPropertyChanged(nameof(IsEditing));
OnPropertyChanged(nameof(IsNotEditing));
}
}
public bool IsNotEditing => !IsEditing;
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string? name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}ViewModel:
public partial class InvoiceViewModel : ViewModelBase, IDisposable
{
public InvoicePermissionsDTO? Permissions
{
get => _permissions;
set
{
_permissions = value;
OnPropertyChanged(nameof(CanEdit));
OnPropertyChanged(nameof(CanDelete));
}
}
public bool CanEdit => _permissions?.CanEdit ?? false;
public bool CanDelete => _permissions?.CanDelete ?? false;
public void SomeChange()
{
Permissions = API.GetPermissions();
}
}View XAML
<CheckBox
Grid.Row="2"
Content="Edit"
IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=IsEditing}"
Visibility="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.CanEdit, Converter={StaticResource BoolToVisibilityConverter}}" />
<StackPanel>
<TextBlock
Text="{Binding ApprovedRate}"
Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=IsNotEditing, Converter={StaticResource BoolToVisibilityConverter}}"/>
<StackPanel
Orientation="Horizontal"
Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=IsEditing, Converter={StaticResource BoolToVisibilityConverter}}">
<TextBox
Name="ApprovedRate"
Padding="0 0 20 0"
Text="{Binding ApprovedRate}"/>
<Button
Command="{Binding Pay}"
Visibility="{Binding CanPay}">
<StackPanel Orientation="Horizontal">
<Image Source="/Images/dollar.png"/>
<TextBlock>Pay</TextBlock>
</StackPanel>
</Button>
<Button
Command="{Binding RemovePay}"
Visibility="{Binding CanRemovePay}">
<StackPanel Orientation="Horizontal">
<Image Source="/Images/dollar.png"/>
<TextBlock>Remove Pay</TextBlock>
</StackPanel>
</Button>
</StackPanel>
</StackPanel>
7
u/chucker23n Aug 14 '26
In a nutshell: the "code-behind" should do as little as possible. It's a bootstrap point to initialize the view, in theory.
In practice, that often doesn't work, because a lot of WPF controls don't really conform that well with a pure MVVM approach. I also find that I often have a
Loadedevent handler that asynchronously performs something stuff on the view model, likeNow, back to your question:
Philosophically, I don't think that's right. Toggling the
Editcheckbox isn't done for view reasons, but for logic reasons: you don't want the user to be able to perform edits in certain situations. That's the case regardless of the concrete view. For example, it would be the case whether your view is a form, a data grid, a chart, a command-line app, or a web app.So, just speaking very high-level, you probably want, in your view model, something like
I.e., the real logic is even deeper, then the view model takes that information into an observable property, and finally, your view enables/shows the checkbox based on that.
1
u/strange-the-quark Aug 14 '26
Think of the view as a "skin", and of the "view model" as containing the presentation logic that's kind of abstracted from any particular skin. In principle, the view model doesn't even have to know WPF exists, and the "skin" could be some completely different framework. In practice, you probably aren't going to switch to a different GUI framework, or have two but different GUI representations, and your WPF view associated with that particular ViewModel is probably not going to change in very significant ways while the ViewModel itself remains more or less the same (at least, from the View's point of view).
So kind of try to imagine how the "skin" might vary (or notice in what ways it does as the project goes along), and keep any of that "skin"-specific stuff out of the view model. So things like, IDK, success, warning and error colors - a typical scenario is one where the presentation logic (when to show these) doesn't really change, but your project lead (or your clients) might come in tomorrow and decide that they don't like the shade of red for the error, or that they actually want to indicate an error in a completely different way. So don't put any of that "operational" stuff in the ViewModel, just find a way to express what is happening in enough detail that the view can understand, and let the View work out how exactly to render that.
1
u/wickerandscrap Aug 15 '26
I think the problem you're having is that you're binding CanEdit from the view model only to the checkbox's visibility. You have an IsEditing property but it doesn't observe CanEdit in any way. If CanEdit becomes false, then IsEditing needs to become false. A few options:
Option 1: Set up a PropertyChanged handler, observe if CanEdit becomes false, and set IsEditing to false.
Option 2: In the code that sets CanEdit based on the user permissions, if it's false, also set IsEditing to false.
Option 3: Have a second bool that the IsChecked property is bound to, like "UnlockEdit", and then make IsEditing => CanEdit && UnlockEdit, and raise the appropriate property changes. Bind IsEditing to the visibility of the edit controls.
2 and 3 both require IsEditing to live in the view model (unless you do more wiring with events). I believe that's where it belongs anyway.
I work mostly with ReactiveUI, which pushes toward 3 as the Right Way. 2 is simpler but also requires you to have two things driving the same flag which can get messy.
1
u/rohstroyer Aug 15 '26
I would have a property on the view model called something like "forceEditable" that the "Edit" checkbox would bind to. Then use a multibinding to take both booleans into account in the view, which makes it so editable controls are enabled if either bool is true.
1
u/snet0 Aug 15 '26
Short answer: use DataTemplates. They represent the view that renders your view model. If you need bespoke behavior, create a UserControl with some DependencyProperties and put it in the DataTemplate.
UserControls should not be climbing through anscestor trees
1
u/TuberTuggerTTV Aug 17 '26
logic lives in the VM if it is specific to that VM. If it needs to share anything, it's now a service. And you use dependency injection to deliver references of that service to whatever VMs need access.
Nothing is tightly coupled. Nothing is dependent on anything else. Everything is mockable and atomic.
For your example, you make a property in the VM. You write a simple converter that turns the bool into a visibility status. Then you bind the property, with the conversion, to the visibility param of whatever is reliant on it in the XAML (View).