Possible way to reduce translation properties with MVVM in WPF - c#

I'm doing refactoring for our app. We currently have 2 languages supported, where the logic is sitting inside TranslationService, injected through DI container (using Prism if matters) into View models.
In order to bind the translation to the text property there is tons of properties in the view model, e.g.
public string SomeText => _translationService.GetTranslation("someText");
public string AnotherText => _translationService.GetTranslation("notherText");
And the binding is happening as usual
<TextBlock Text="{Binding SomeText}" HorizontalAlignment="Center" />
Is there a way to reduce those properties? For example to bind the Text property to the GetTranslation method with a parameter?
I've seen how to use ObjectDataProvider but this doesn't really help me out, because the method parameters are hard-coded as per my understanding.

You may declare a helper class with a single indexer property like
public class Translation
{
private readonly TranslationService translationService;
public Translation(TranslationService service)
{
translationService = service;
}
public string this[string key]
{
get { return translationService.GetTranslation(key); }
}
}
which would be used as a single property in your view model:
public class ViewModel
{
public ViewModel()
{
Translation = new Translation(_translationService);
}
public Translation Translation { get; }
}
You would bind it like this:
<TextBlock Text="{Binding Translation[someText]}"/>

Related

How to pass a ref to a viewmodel correctly

I've created a Textbox with placeholder text and a clear button. I've implemented it using a view model for the data context, and using a style with target type TextBox. In xaml, using it is pretty simple.
<TextBox DataContext="{Binding NameBox}" Style="{StaticResource placeholder}"/>
The way I've implemented the view model, though, smells funny to me:
public class PlaceholderTextBoxViewModel : NotifiableViewModelBase {
private string text;
public string Text {
get => text;
set {
text = value;
OnTextChange(text);
}
}
public string PlaceholderText { get; set; }
public RelayCommand ClearCommand => new RelayCommand(() => Text = "");
private event Action<string> OnTextChange;
public PlaceholderTextBoxViewModel(ref string text, string placeholderText, Action<string> changeHandler = null) {
OnTextChange = changeHandler ?? (_ => { });
Text = text;
PlaceholderText = placeholderText;
}
}
In case it doesn't smell too bad to you yet, check out how it's used
private string _name;
public string Name {
get => _name;
set {
_name = value;
System.Console.WriteLine(_name); // needed to silence auto prop error
}
}
public PlaceholderTextBoxViewModel NameBox { get; }
// in the constructor...
NameBox = new PlaceholderTextBoxViewModel(ref _name, "Exam Name", t => Name = t);
It definitely doesn't seem right that I need to pass an explicit setter (the changeHandler) to the PlaceholderTextBoxViewModel. It seems, indeed, that the ref I'm passing is never really used (and is only necessary at all -- though not as a ref -- if there is to be pre-existing text in the box).
I've never used refs before and I must be doing something wrong. I have also tried pointing everything that uses the Name property (in the final code excerpt) to the _name field but that doesn't work, the field isn't properly updated, or at least isn't "communicating" its updates (in various uses, CanExecutes are not updated, SearchPredicates are not refreshed, etc). I'm using MVVMLight, and I imagine that changing a field's value doesn't trigger OnPropertyChanged -- if the field's value is even changing at all.
How do I get the ref to work correctly? Am I doing this completely wrong?
I understand that there are other ways to implement this TextBox with its clear command, even in pure MVVM (namely, if I put the ClearCommand in the consuming VM instead of the textbox's VM itself, then the textbox doesn't need to have a VM at all). But I'd really like to know how to make sense of my attempted solution, if only for a better understanding of C# and of refs.
Problem here seems to be an architectural one. MVVM is a tiered architecture that looks like this:
Model -> View Model -> View
Model is the lowest tier, view is the highest. More importantly, each tier does not have any direct visibility into any of the tiers above it.
The problem in your example is that you've broken separation of concerns. You have a parent class creating the PlaceholderTextBoxViewModel, which implies it's in the view model. However, that same class contains a "Name" property, which is actually data that should be in your model layer. Your existing architecture is such that your view model cannot see the data layer, so you've effectively had to set up your own property change notification mechanism, using the ref and delegate, to keep your model and view model synchronized.
Throw it all out, and start again. Your model should contain POCOs, so start with something like this:
public class MyModel
{
public string Name {get; set;}
}
Then, when you create your view model, pass an instance of this class into its constructor so that it has visibility:
public class MyViewModel : NotifiableViewModelBase
{
private MyModel Model;
public MyViewModel(MyModel model) => this.Model = model;
public string Text
{
get => this.Model.Name;
set
{
this.Model.Name = value;
RaisePropertyChanged(() => this.Text);
}
}
// ... etc ....
}
I've stuck to your nomenclature of using "Name" in the model and "Text" in the view model, in practice they're usually the same, but that's up to you. Either way, you still have property change notification in your view model, and it's the view model layer updating the model layer.
Obviously there are lots of variations on this. If you don't want changes to propagate through to your model layer immediately (and there are plenty of cases where you may not want that) then give Text a backing field (_Text) and only do the synchronization at the points your want it to occur. And of course, if you want to go one step further then your model classes could instead implement interfaces, and you can use dependency injection to inject those interfaces into the view model classes instead of giving them access to the actual implementations themselves.
Above all else, keep in mind that the sole purpose of the view model is to prepare the model layer data for consumption by the view. Anything else...data, domain, business logic etc...all of that belongs in your model layer, which shouldn't have any visibility into the view model layer at all.
The ref would only make sense, if you are going to change the value.
In this case you can use the OnTextChange event.
public PlaceholderTextBoxViewModel(ref string text, string placeholderText, Action<string> changeHandler = null)
{
OnTextChange = newValue =>
{
text = newValue; // <- value back to the ref
changeHandler?.Invoke(newValue);
}
Text = text;
PlaceholderText = placeholderText;
}
BTW your solution is somehow much too complicated. Keep the ViewModel as simple and abstract as possible. In this case a simple Name property is enough.
Leave it up the the UI developers which control they use and how they will implement a clear the control logic.
Here an example
ViewModel
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
namespace WpfApp1
{
public class MainViewModel : ReactiveObject
{
[Reactive] public string Name { get; set; }
}
}
View
<Window
x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp1"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Window.DataContext>
<local:MainViewModel />
</Window.DataContext>
<Grid>
<StackPanel
Width="200"
VerticalAlignment="Center">
<Label Content="{Binding Name}" />
<DockPanel>
<Button
DockPanel.Dock="Right"
Content="x"
Width="20"
Click="NameTextBoxClearButton_Click"/>
<TextBox x:Name="NameTextBox"
Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
TextWrapping="Wrap" />
</DockPanel>
</StackPanel>
</Grid>
</Window>
View CodeBehind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void NameTextBoxClearButton_Click( object sender, RoutedEventArgs e )
{
NameTextBox.Text = string.Empty;
}
}
The simplest solution would be to correct your binding. You don't have to manually forward the data by trying to implement your own change notification system.
Just make sure that your data source always implements INotifyPropertyChanged and properly raises the INotifyPropertyChanged.PropertyChanged event from each property set method. Then bind directly to this properties:
class PlaceholderTextBoxViewModel : INotifyPropertyChanged
{
private string text;
public string Text
{
get => this.text;
set
{
this.text = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
The binding syntax allows to reference nested properties.
In your special case, the {Binding} expression must be:
<TextBox DataContext="{Binding NameBox.Text}" />
Now the TextBox.Text value is automatically propagated to the PlaceholderTextBoxViewModel.Text property and the constructor becomes parameterless.

How do I provide a generic child property

We have an Entity framework model, which contains classes named QuoteStatus and SystemStatus, which model the status of a quote and a system respectively. Each of these classes has a navigation property, which is a collection that contains the emails of people who are to be notified when the status changes. The QuoteStatus class looks like this (simplified)...
public class QuoteStatus {
public int ID { get; set; }
public string Name { get; set; }
public List<QuoteStatusNotification> QuoteStatusNotifications;
}
public class QuoteStatusNotification {
public int ID { get; set; }
public string Email { get; set; }
}
The SystemStatus and SystemStatusNotification classes are remarkably similar.
Now, we want to have a WPF window that can be used to maintain both types of statuses (and any more that come along in the future). The idea is to have a dropdown control at the top of the window, where the user specifies the type of status to be shown (quote or system), and the value is sent to the view model.
The view model would have private variables for the data...
private List<QuoteStatus> _quoteStatuses;
private List<SystemStatus> _systemStatuses;
We want the view model to have a public Statuses property, which can be bound to a grid on the view. Depending on what value the user chooses in the dropdown, the Statuses property would contain either the _quoteStatuses collection, or the _systemStatuses collection.
We did that by creating a base Status class, and having the QuoteStatus and SystemStatus classes inherit from it. That was fine.
We ran into a problem with the child collections. We want the Status base class to have a StatusNotifications collection, which will be a collection of either the QuoteStatusNotification class, or the SystemStatusNotification class. We couldn't work out how to create that StatusNotifications collection.
From another thread here (see the second suggestion in the accepted answer), it looks like I might be able to do this with covariance, but I can't get my head round how to do it.
Anyone able to explain this?
Simple inheritance:
public class StatusBaseClass
{
public List<StatusNotification> StatusNotifications;
}
public class QuoteStatus : StatusBaseClass
{
}
public class SystemStatus : StatusBaseClass
{
}
public class StatusNotification
{
}
public class QuoteStatusNotification : StatusNotification
{
}
public class SystemtatusNotification : StatusNotification
{
}
You can add a QuoteStatusNotificatio or SystemStatusNotification to the base class list
What you can do that is really neat in your xaml is provide different UI for the two classes in a list view for example. See here: DataTemplate for each DataType in a GridViewColumn CellTemplate
For example:
<ListView ItemsSource="{Binding Statuses}">
<ListView.Resources>
<DataTemplate DataType="{x:Type viewModel:SystemStatus}">
</DataTemplate>
<DataTemplate DataType="{x:Type viewModel:QuoteStatus}">
</DataTemplate>
</ListView.Resources>
</ListView>
A bit more detail of what you're trying to do and may be able to help a bit more.
Create a base class that has the properties that are common across both types. Then you can pass
List<StatusBaseClass> statuses;
You can put either type into this list.
If it is a mixed list then you can get the individual types out by:
var quoteStatuses = statuses.OfType<QuoteStatus>();
var systemStatuses = statuses.OfType<SystemStatus>();

Sharing data between different ViewModels

I'm trying to develop an easy MVVM project that it has two windows:
The first window is a text editor, where I bind some properties such as FontSize or BackgroundColor:
<TextBlock FontSize="{Binding EditorFontSize}"></TextBlock>
its DataContext is MainWindowViewModel:
public class MainWindowViewModel : BindableBase
{
public int EditorFontSize
{
get { return _editorFontSize; }
set { SetProperty(ref _editorFontSize, value); }
}
.....
The second window is the option window, where I have an slider for changing the font size:
<Slider Maximum="30" Minimum="10" Value="{Binding EditorFontSize }" ></Slider>
its DataContext is OptionViewModel:
public class OptionViewModel: BindableBase
{
public int EditorFontSize
{
get { return _editorFontSize; }
set { SetProperty(ref _editorFontSize, value); }
}
.....
My problem is that I have to get the value of the slider in the option window and then I have to modify the FontSize property of my TextBlock with this value. But I don't know how to send the font size from OptionViewModel to MainViewModel.
I think that I should use:
A shared model
A model in MainWindowViewModel and a ref of this model in OptionViewModel
Other systems like notifications, messages ...
I hope that you can help me. It's my first MVVM project and English isn't my main language :S
Thanks
Another option is to store such "shared" variables in a SessionContext-class of some kind:
public interface ISessionContext: INotifyPropertyChanged
{
int EditorFontSize { get;set; }
}
Then, inject this into your viewmodels (you are using Dependency Injection, right?) and register to the PropertyChanged event:
public class MainWindowViewModel
{
public MainWindowViewModel(ISessionContext sessionContext)
{
sessionContext.PropertyChanged += OnSessionContextPropertyChanged;
}
private void OnSessionContextPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "EditorFontSize")
{
this.EditorFontSize = sessionContext.EditorFontSize;
}
}
}
There are many ways to communicate between view models and a lot of points what the point is the best. You can see how it is done:
using MVVMLight
in Prism
by Caliburn
In my view, the best approach is using EventAggregator pattern of Prism framework. The Prism simplifies MVVM pattern. However, if you have not used Prism, you can use Rachel Lim's tutorial - simplified version of EventAggregator pattern by Rachel Lim.. I highly recommend you Rachel Lim's approach.
If you use Rachel Lim's tutorial, then you should create a common class:
public static class EventSystem
{...Here Publish and Subscribe methods to event...}
And publish an event into your OptionViewModel:
eventAggregator.GetEvent<ChangeStockEvent>().Publish(
new TickerSymbolSelectedMessage{ StockSymbol = “STOCK0” });
then you subscribe in constructor of another your MainViewModel to an event:
eventAggregator.GetEvent<ChangeStockEvent>().Subscribe(ShowNews);
public void ShowNews(TickerSymbolSelectedMessage msg)
{
// Handle Event
}
The Rachel Lim's simplified approach is the best approach that I've ever seen. However, if you want to create a big application, then you should read this article by Magnus Montin and at CSharpcorner with an example.
Update: For versions of Prism later than 5 CompositePresentationEvent is depreciated and completely removed in version 6, so you will need to change it to PubSubEvent everything else can stay the same.
I have done a big MVVM application with WPF. I have a lot of windows and I had the same problem. My solution maybe isn't very elegant, but it works perfectly.
First solution: I have done one unique ViewModel, splitting it in various file using a partial class.
All these files start with:
namespace MyVMNameSpace
{
public partial class MainWindowViewModel : DevExpress.Mvvm.ViewModelBase
{
...
}
}
I'm using DevExpress, but, looking your code you have to try:
namespace MyVMNameSpace
{
public partial class MainWindowViewModel : BindableBase
{
...
}
}
Second solution: Anyway, I have also a couple of different ViewModel to manage some of these windows. In this case, if I have some variables to read from one ViewModel to another, I set these variables as static.
Example:
public static event EventHandler ListCOMChanged;
private static List<string> p_ListCOM;
public static List<string> ListCOM
{
get { return p_ListCOM; }
set
{
p_ListCOM = value;
if (ListCOMChanged != null)
ListCOMChanged(null, EventArgs.Empty);
}
}
Maybe the second solution is simplier and still ok for your need.
I hope this is clear. Ask me more details, if you want.
I'm not a MVVM pro myself, but what I've worked around with problems like this is,
having a main class that has all other view models as properties, and setting this class as data context of all the windows, I don't know if its good or bad but for your case it seems enough.
For a more sophisticated solution see this
For the simpler one,
You can do something like this,
public class MainViewModel : BindableBase
{
FirstViewModel firstViewModel;
public FirstViewModel FirstViewModel
{
get
{
return firstViewModel;
}
set
{
firstViewModel = value;
}
}
public SecondViewModel SecondViewModel
{
get
{
return secondViewModel;
}
set
{
secondViewModel = value;
}
}
SecondViewModel secondViewModel;
public MainViewModel()
{
firstViewModel = new FirstViewModel();
secondViewModel = new SecondViewModel();
}
}
now you have to make another constructor for your OptionWindow passing a view model.
public SecondWindow(BindableBase viewModel)
{
InitializeComponent();
this.DataContext = viewModel;
}
this is to make sure that both windows work on the same instance of a view model.
Now, just wherever you're opening the second window use these two lines
var window = new SecondWindow((ViewModelBase)this.DataContext);
window.Show();
now you're passing the First Window's view model to the Second window, so that they work on the same instance of the MainViewModel.
Everything is done, just you've to address to binding as
<TextBlock FontSize="{Binding FirstViewModel.EditorFontSize}"></TextBlock>
<TextBlock FontSize="{Binding SecondViewModel.EditorFontSize}"></TextBlock>
and no need to say that the data context of First window is MainViewModel
In MVVM, models are the shared data store. I would persist the font size in the OptionsModel, which implements INotifyPropertyChanged. Any viewmodel interested in font size subscribes to PropertyChanged.
class OptionsModel : BindableBase
{
public int FontSize {get; set;} // Assuming that BindableBase makes this setter invokes NotifyPropertyChanged
}
In the ViewModels that need to be updated when FontSize changes:
internal void Initialize(OptionsModel model)
{
this.model = model;
model.PropertyChanged += ModelPropertyChanged;
// Initialize properties with data from the model
}
private void ModelPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(OptionsModel.FontSize))
{
// Update properties with data from the model
}
}
I'm new to WPF and I've come up with a solution to this and I'm curious of more knowledgeable people's thoughts about what's right and wrong with it.
I have an Exams tab and a Templates tab. In my simple proof of concept, I want each tab to "own" an Exam object, and to be able to access the other tab's Exam.
I define the ViewModel for each tab as static because if it's a normal instance property, I don't know how one tab would get the actual instance of the other tab. It feels wrong to me, though it's working.
namespace Gui.Tabs.ExamsTab {
public class GuiExam: INotifyPropertyChanged {
private string _name = "Default exam name";
public string Name {
get => _name;
set {
_name = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName="") {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public partial class ExamsHome : Page {
public ExamsHome() {
InitializeComponent();
DataContext = ViewModel;
}
public static readonly ExamsTabViewModel ViewModel = new ExamsTabViewModel();
}
public class ExamsTabViewModel {
public GuiExam ExamsTabExam { get; set; } = new GuiExam() { Name = "Exam from Exams Tab" };
public GuiExam FromTemplatesTab { get => TemplatesHome.ViewModel.TemplatesTabExam; }
}
}
namespace Gui.Tabs.TemplatesTab {
public partial class TemplatesHome : Page {
public TemplatesHome() {
InitializeComponent();
DataContext = ViewModel;
}
public static readonly TemplatesTabViewModel ViewModel = new TemplatesTabViewModel();
}
public class TemplatesTabViewModel {
public GuiExam TemplatesTabExam { get; set; } = new GuiExam() { Name = "Exam from Templates Tab" };
public GuiExam FromExamTab { get => ExamsHome.ViewModel.ExamsTabExam; }
}
}
And then everything is accessible in the xaml:
TemplatesHome.xaml (excerpt)
<StackPanel Grid.Row="0">
<Label Content="From Exams Tab:"/>
<Label FontWeight="Bold" Content="{Binding FromExamTab.Name}"/>
</StackPanel>
<StackPanel Grid.Row="1">
<Label Content="Local Content:"/>
<TextBox Text="{Binding TemplatesTabExam.Name, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Center" Width="200" FontSize="16"/>
</StackPanel>
ExamsHome.xaml (excerpt)
<StackPanel Grid.Row="0">
<Label Content="Local Content:"/>
<TextBox Text="{Binding ExamsTabExam.Name, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Center" Width="200" FontSize="16"/>
</StackPanel>
<StackPanel Grid.Row="1">
<Label Content="From Templates Tab:"/>
<Label FontWeight="Bold" Content="{Binding FromTemplatesTab.Name}"/>
</StackPanel>

Correct way to implement MVVM Design pattern when using SQLite

So lets say I have a SQLite database of Person's with property Name
Public Class Person
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
And now I have a view with a ListBox Displaying those names
<ListBox ItemSource={Binding People}>
<ListBox.ItemTemplate>
<DataTemplate>
<Label Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
and my Views DataContext is PeopleViewVM
Public Class PeopleViewVM
{
Public PeopleViewVM
{
//Do my SQLite stuff,
// Get IEnumerable Person's
// Create Observable Collection of People
}
private ObservableCollection<Person> _people;
public ObservableCollection<Person> People
{
get { return _people; }
set
{
_people = value;
RaisePropertyChanged();
}
}
}
Now I understand this is a simple example. But I am unsure whether this is the correct implementation of the MVVM design pattern.
If Person my model this means that the view is binding directly to the model when it is binding to the property name. If I change the name of a person in code behind this won't be reflected in the view. What is the correct way to do this example using the MVVM design pattern?
That can be the "correct" implementation, based on your requirements. I wouldn't say that there's a "correct", and "incorrect" for this issue. More like: would it be better for my scenario, or not?
People choose to bind models against view directly based on their requirements, and how they feel. Sometimes I like to simplify my models, and wrap them into "PersonViewModel", in order to expose more relevant properties, and not pollute the Model.
If that doesn't suit you, you can download ReSharper(takes care of "trying" to keep the View & viewmodel synchronized), or alternatively you can encapsulate your model further, and create a "proxy" object, as such:
Public Class PersonViewModel
{
readonly Person _person;
Public PersonViewModel(Person person)
{
_person = person;
}
public string Name
{
get { return _person.Name; }
set
{
_person.Name = value;
RaisePropertyChanged();
}
}
which seems to be pointless, but helps to keep the view and model even more separate, in case of model entities that change often. ReSharper does take care of most cases, in my experience.

WPF MVVM one view multiple object types

Currently I'm learning WPF with MVVM and have maybe a crazy idea...
I have several simple classes:
public class Car : IProduct
{
public int Id {get;set;}
public string Brand {get;set;}
// some custom properies
}
public class Seat : IProduct
{
public int Id {get;set;}
public string Brand {get;set;}
// some custom properties
}
Idea was that I have one editor view for diferent models.
public class ProductViewModel<T> : ViewModelBase, IProductViewModel<T> where T : IProduct
{
private T m_editorModel;
public T EditorModel
{
get { return m_editorModel; }
set
{
m_editorModel = value;
RaisePropertyChanged(() => EditorModel);
}
}
public Type ModelType
{
get { return typeof(T); }
}
}
Which can be afterwords set to view DataContext
viewModel = ViewModelFactory.CreateViewModel<IProductViewModel<Car>>();
view = ViewFactory.CreateView<ProductView>();
view.DataContext = viewModel;
// etc...
The problem is that I don't know is it possible or how to create in run time
ObservableCollection of same object EditorModel.
Is it maybe easier path to create for each class it's own view and viewmodel or something totally different?
In MVVM in general [I'm not speaking for everyone here], you don't want to be instantiating views from code. Instead we work with and manipulate data. To change views, we change view models and often set the connections between the two in simple DataTemplates:
<DataTemplate DataType="{x:Type ViewModels:MainViewModel}">
<Views:MainView />
</DataTemplate>
...
<DataTemplate DataType="{x:Type ViewModels:UsersViewModel}">
<Views:UsersView />
</DataTemplate>
This way, we don't need to explicitly set any DataContexts. We can simply have a BaseViewModel property that each view model extends:
public BaseViewModel ViewModel
{
get { return viewModel; }
set { if (viewModel != value) { viewModel = value; NotifyPropertyChanged("ViewModel"); } }
}
We can change view models and therefore views like this:
ViewModel = new UsersView();
Then we can display the relating view in a ContentControl like this:
<ContentControl Content="{Binding ViewModel}" />
Finally, in my opinion, you really should create a view model for each view... the view model's sole job is to provide the data and functionality for each view. So unless you have multiple identical views, you'd need different view models. It is however possible to have one view model that all of the views bind to, but I'd advise against that for large applications.

Categories

Resources