I am using WPF (C#) for the first time and this I've encountered my first "real" design choice. I have a main window and when the user enters some data and presses the "plot" Button, a new window will come up showing a graph.
This graph window I am defining myself with a combination of xaml and the code-behind file. The issue is that 2 parameters this window has is the x axis title and the y axis title. So, these should be "parameters" to making this window.
I am confused by this because I'm using MVVM and I have a "ViewModel" for the window called GraphWindowPresenter and a "View" for the class called GraphWindowView.
At first, I tried to have an xAxis property and a yAxis property in my GraphWindowPresenter but that will not work since I need to "bind" to these values upon construction of the GraphWindowView. Additionally, this approach would require that my GraphWindowPresenter take an xAxis parameter and a yAxis parameter which is problamatic as well since I just create an instance of the class in the xaml of GraphWindowView.
I'm thinking of a possible soltuion that I can just have my GraphWindowView take the xAxis and yAxis parameters but doesn't this violate MVVM? I would rather not do that.
Note: This is similar to this post MVVM: Binding a ViewModel which takes constructor args to a UserControl. But in my scenario it is tricky since I have a parent window and a pop up child window.
Question: What is the best approach to this design issue? What are the "best practices" regarding this scenario?
Possible Answer:
Is this the correct use of dependency properties that you described? Is this a "clean" solution?
private void doGraph()
{
if (log == null) // if a log is not loaded
{
MessageBoxResult mbr = MessageBox.Show("A log file must be " +
"loaded before plotting.",
"Warning",
MessageBoxButton.OK,
MessageBoxImage.Exclamation);
return;
}
// NOW MUST PRESENT GRAPH WINDOW
GraphWindowView gwv = new GraphWindowView();
gwv.xAxis = X_AXIS_VALUE:
gwv.yAxis = Y_AXIS_VALUE;
gwv.Show();
}
And in my GraphWindowView class I have the code:
public partial class GraphWindowView : Window
{
// Using a DependencyProperty as the backing store for yAxis.
public static readonly DependencyProperty yAxisProperty =
DependencyProperty.Register("yAxis", typeof(string), typeof(GraphWindowView));
// Using a DependencyProperty as the backing store for xAxis.
public static readonly DependencyProperty xAxisProperty =
DependencyProperty.Register("xAxis", typeof(string), typeof(GraphWindowView));
public string xAxis
{
get { return (string)GetValue(xAxisProperty); }
set { SetValue(xAxisProperty, value); }
}
public string yAxis
{
get { return (string)GetValue(yAxisProperty); }
set { SetValue(yAxisProperty, value); }
}
public GraphWindowView()
{
InitializeComponent();
}
}
You can you userSetting properties
One my application have same scenario in that i have mainWindow that accept HostAddress,Port value and it will use another window when i click connect so i am using userSetting properties. I am also using MVVM pattern check code snippet below
XAML:
<TextBox Width="120" Canvas.Left="132" Canvas.Top="16" Text="{Binding Path=Server,Mode=TwoWay}"/>
<TextBox Width="120" Canvas.Left="132" Canvas.Top="42" Text="{Binding Path=DisplayPort,Mode=TwoWay}"/>
<TextBox Width="120" Canvas.Left="132" Canvas.Top="69" Text="{Binding Path=CtrlPort,Mode=TwoWay}"/>
<Button Content="Launch" Name="btnLaunch" Command="{Binding Path=appSetting}" Canvas.Left="132" Canvas.Top="100" Width="120" Height="51" Click="btnLaunch_Click" />
VIEWMODE:
public class SettingsViewModel : ViewModelBase
{
private Settings _settings { get; set; }
public SettingsViewModel()
{
appSetting = new RelayCommand(this.AppSettingsCommand);
_settings = ApplicationTest.Properties.Settings.Default;
}
private string _server = Settings.Default.Server;
public string Server
{
get { return this._server; }
set
{
if (this._server != value)
{
this._server = value;
OnPropertyChanged("Server");
}
}
}
private string _displayPort = Settings.Default.DisplayPort;
public string DisplayPort
{
get { return this._displayPort; }
set
{
if (this._displayPort != value)
{
this._displayPort = value;
OnPropertyChanged("DisplayPort");
}
}
}
private string _ctrlPort = Settings.Default.CtrlPort;
public string CtrlPort
{
get { return this._ctrlPort; }
set
{
if (this._ctrlPort != value)
{
this._ctrlPort = value;
OnPropertyChanged("DisplayPort");
}
}
}
public RelayCommand appSetting
{
get;
set;
}
private void AppSettingsCommand()
{
this._settings.Server = this.Server;
this._settings.DisplayPort = this.DisplayPort;
this._settings.CtrlPort = this.CtrlPort;
this._settings.Save();
}
Related
I am very new to WPF and couldn't get my head around this so checked couple tutorials and kinda merged them together and I am here with this mess. Dont really know how should I describe my issue around so I decided to write here.
What I am working on;
Using a WPF I got a menu opening UserControls inside the Main Window.
When Main Window starts I am starting a thread like this so I get a loop
private void MainLoop()
{
Thread th = Thread.CurrentThread;
while (th.ThreadState != ThreadState.AbortRequested &&
th.ThreadState != ThreadState.Aborted)
{
if (bMainOk)
{
switch (activeUC)
{
case "ucDurum":
LoopControl.ucDurumLoop(plc, connectionString);
break;
case "ucAyarlar":
//LoopControl.ucAyarlarLoop();
break;
default:
break;
}
}
Thread.Sleep(2000);
}
}
That LoopControl class has functions inside that are looping depending on the active UserControl.
public class LoopControl : ObservableObject
{
public static void ucDurumLoop(ActUtlType plc, string connectionString)
{
DurumVM durum = new DurumVM();
// The values do change before this lines, I didnt put them for the sake of clarity
durum.RaporAktif = "true";
durum.RaporAdedi = arrayData[0].ToString();
durum.BufferPercent = "%" + (float)arrayData[0] / 250 * 100;
durum.PlcSonCounter = arrayData[4].ToString();
durum.SqlSonCounter = sonCntr.ToString();
}
}
Which is Connected to a Main ViewModel then sub ViewModels like so
class MainVM
{
public DurumVM Durum { get; private set; }
public AyarlarVM Ayarlar { get; private set; }
public MainVM()
{
Durum = new DurumVM();
Ayarlar = new AyarlarVM();
}
}
public class DurumVM : ObservableObject
{
#region PLCVars
private bool _raporAktif;
private string _raporAdedi;
private string _bufferPercent;
private string _plcSonCounter;
private string _sqlSonCounter;
#endregion
#region PLCGetSets
public string RaporAktif
{
get
{
if (_raporAktif)
return "Düzenlenecek True";
return "Düzenlenecek False";
}
set
{
_raporAktif = Convert.ToBoolean(value);
OnPropertyChanged("RaporAktif");
}
}
public string RaporAdedi
{
get
{
if (string.IsNullOrEmpty(_raporAdedi))
return "Zeroh";
return _raporAdedi;
}
set
{
_raporAdedi = value;
OnPropertyChanged("RaporAdedi");
}
}
public string BufferPercent
{
get
{
if (string.IsNullOrEmpty(_bufferPercent))
return "%0";
return _bufferPercent;
}
set
{
_bufferPercent = (value.Length <= 5 ? value : value.Substring(0, 5));
OnPropertyChanged("BufferPercent");
}
}
public string PlcSonCounter
{
get
{
if (string.IsNullOrEmpty(_plcSonCounter))
return "0";
return _plcSonCounter;
}
set
{
_plcSonCounter = value;
OnPropertyChanged("PlcSonCounter");
}
}
public string SqlSonCounter
{
get
{
if (string.IsNullOrEmpty(_sqlSonCounter))
return "0";
return _sqlSonCounter;
}
set
{
_sqlSonCounter = value;
OnPropertyChanged("SqlSonCounter");
}
}
#endregion
}
And the user control are bound to these values:
<StackPanel>
<DockPanel>
<Label Content="Aktif mi? :" VerticalAlignment="Center"/>
<TextBlock Text="{Binding RaporAktif, UpdateSourceTrigger=PropertyChanged}" DockPanel.Dock="Right" Margin="0,0,25,0" HorizontalAlignment="Right" VerticalAlignment="Center">
<TextBlock.Effect>
<DropShadowEffect/>
</TextBlock.Effect>
</TextBlock>
</DockPanel>
...
public partial class ucDurum : UserControl
{
MainVM viewModel = new MainVM();
//LoopControl viewModel = new LoopControl();
public ucDurum()
{
InitializeComponent();
this.DataContext = viewModel.Durum;
Control.activeUC = "ucDurum";
}
}
Quick sum:
I got set of user controls and one main loop. Main loop has parts that only works if correct user control is active, connects to somewhere else and gets values then sets these values on a reference, sends it to user control and textblocks the values bound will update
What is wrong that I know:
Practice might be very incorrect. It was looking good in my head but I realized the problem. Mainly due to my lack of C# knowledge. The main loop gets reference of VM sets the datas but never sends them anywhere as I bolded in quick summary. I certain the problem is there since the values I got are correct, when I change values view button etc they do change and update. But VM has no idea about LoopControl.
In MVC I'd return the referenced object then get values on view. In here the values are bound directly and I am kind of lost.
Thanks in advance.
Update:
I'm sorry I wasn't clear enough above the last paragraphs.
What I expect it to do:
LoopControl.ucDurumLoop updates DurumVM using referenced object so the user control "ucDurum" can see it and update TextBlock values accordingly.
What is happening:
I set up the referenced object in LoopControl.ucDurumLoop with the values but that is just an object and stays there. Doesn't go to DurumVM and update values using their Get/Set 's, so values are same and user control "ucDurum" has no idea what is going on on LoopControl.
Well I was being stupid.
Problem was, I was creating new object reference and updating it while I had to reference the one on UserControl.
All I needed was changing a line in LoopControl
public class LoopControl : ObservableObject
{
public static void ucDurumLoop(ActUtlType plc, string connectionString)
{
DurumVM durum = new DurumVM(); // Changing this
DurumVM durum = ucDurum.viewModel; // To this.
durum.RaporAktif = "true";
durum.RaporAdedi = arrayData[0].ToString();
durum.BufferPercent = "%" + (float)arrayData[0] / 250 * 100;
durum.PlcSonCounter = arrayData[4].ToString();
durum.SqlSonCounter = sonCntr.ToString();
}
}
I am having a little Problem with DataBinding to a ListView.
Because I want to have a Listview with MultiSelection I needed to implement a custom class called GenericSelectableItem which stores the Data, and if the cell IsSelected.
First, here is the View Model of the MainPage:
public class MainPageViewModel : BaseViewModel, INotifyPropertyChanged
{
private ObservableCollection<GenericSelectableItem<AudioFile>> _audiofiles = new ObservableCollection<GenericSelectableItem<AudioFile>>();
public ObservableCollection<GenericSelectableItem<AudioFile>> AudioFiles
{
get => _audiofiles ?? new ObservableCollection<GenericSelectableItem<AudioFile>>();
set
{
_audiofiles = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(AudioFiles)));
}
}
}
The Xaml for the MainPage:
<!-- The Content -->
<ListView x:Name="listView" Grid.Row="1" HasUnevenRows="true" RowHeight="-1" ItemsSource="{Binding AudioFiles}" ItemSelected="ListView_OnItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<local:AudioViewCell Audiofile="{Binding Data}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
2 Helper Classes for making a multiselectable ListView:
public class GenericSelectableItem<T> : SelectableItem
{
public GenericSelectableItem(T data)
: base(data)
{
}
public GenericSelectableItem(T data, bool isSelected)
: base(data, isSelected)
{
}
// this is safe as we are just returning the base value
public new T Data
{
get => (T)base.Data;
set => base.Data = value;
}
}
public class SelectableItem : BindableObject
{
public static readonly BindableProperty DataProperty =
BindableProperty.Create(
nameof(Data),
typeof(object),
typeof(SelectableItem),
(object) null);
public static readonly BindableProperty IsSelectedProperty =
BindableProperty.Create(
nameof(IsSelected),
typeof(object),
typeof(SelectableItem),
(object)false);
public SelectableItem(object data)
{
Data = data;
IsSelected = false;
}
public SelectableItem(object data, bool isSelected)
{
Data = data;
IsSelected = isSelected;
}
public object Data
{
get => (object)GetValue(DataProperty);
set => SetValue(DataProperty, value);
}
public bool IsSelected
{
get => (bool)GetValue(IsSelectedProperty);
set => SetValue(IsSelectedProperty, value);
}
}
A Binding Example in AudioViewCell.Xaml:
<Label x:Name="LblFilename" Text="{Binding Filename}"
VerticalTextAlignment="Center"
Style="{StaticResource CellLabel}"/>
The AudioViewCell.cs
public partial class AudioViewCell : ViewCell
{
public static BindableProperty AudiofileProperty = BindableProperty.Create(
propertyName: nameof(Audiofile),
returnType: typeof(AudioFile),
declaringType: typeof(AudioViewCell),
defaultValue: null,
defaultBindingMode: BindingMode.OneWay);
public AudioFile Audiofile
{
get => (AudioFile) GetValue(AudiofileProperty);
set
{
Debug.WriteLine("Audiofile changed");
SetValue(AudiofileProperty, value);
((MenuItemViewModel) BindingContext).Audiofile = value;
}
}
public AudioViewCell()
{
InitializeComponent();
this.BindingContext = new MenuItemViewModel(SlAdditionalData, AwvWaveView);
}
}
And finally the MenuItemViewModel:
public class MenuItemViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private AudioFile _audioFile;
public AudioFile Audiofile
{
get => _audioFile;
set
{
Debug.WriteLine("Setting Audiofile");
_audioFile = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(Audiofile)));
PropertyChanged(this, new PropertyChangedEventArgs(nameof(Filename)));
}
}
public string Filename => Audiofile?.Filename;
}
It seems that the Field Data inside GenericSelectableItem is never set so I think there is something wrong with the binding
Does anyone know a better way or why this is not working?
Thanks alot for your help!!
TL;DR Version: Taking a deep looking on your cell's and 'cellViewModel's source code I've noticed that there's a confusion on bindings handle on your code. You are treating one BindingContext that you set at the AudioViewCell's constructor but it's overridden by the one set automatically by the ListView (that runs after the constructor). So you stand with a ViewCell rendered with no data.
On this image, I tried to show what's going on with your model:
Notice that yellow circular arrow at left, it's you defining the binding context at the constructor. That's overridden later by the red arrows (set after the listview renders).
To make it works the way you've coded, follow these steps:
Get rid of the AudiofileProperty at AudiofileViewCell, you will not need it;
Create an overload to MenuItemViewModel's constructor to receive the "AudioFile" (the MenuItemViewModel class is your real BindingContext);
Override the OnBindingContextChanged method to extract the new one Data field and send it as a parameter to the constructor of a new instance of MenuItemViewModel;
Set this new Instance of MenuItemViewModel as BindingContext of your inner View (It's a StackLayout called slRoot according to your source code)
Here's the steps code:
2:
public class MenuItemViewModel : INotifyPropertyChanged
{
// ...
public void SetAudiofile(AudioFile data)
{
Audiofile = data;
}
// ...
}
3 and 4:
public partial class AudioViewCell : ViewCell
{
// ...
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
// * I'm not sure if it's ok create a new instance to your binding context here, the old one ca be kept on memory due it's subscription. Think about create a method to set just the Audiofile property
slRoot.BindingContext = new MenuItemViewModel( thing, thing, ((GenericSelectableItem<AudioFile>)BindingContext).Data);
}
// ...
}
I've tested and it works, but it's far from an ideal clean solution.
If your intent is to reuse this cell, I think you should expose the properties that can be or not bound, let the need of it says what will be shown. The view cell should only handle visual layout / behavior, don't matter what data is on it.
P.S.: Sorry for my bad English, I hope it can be understandable.
I'm creating a WPF program and I have created a custom Usercontrol and custom Textbox
When I rebuild my solution in visual studio i get this error.
Cannot set Name attribute value 'SearchT' on element 'HintTextBox'. 'HintTextBox' is under the scope of element 'ClickableControl', which already had a name registered when it was defined in another scope
I don't know what I need to do. Or what I did wrong? can someone help me? The classes below are the usercontrol and the hinttextbox, the last one is how I implmented them in xaml.
This is how I put the textbox in my Usercontrol
TEXTBOX = HintTextBox:
namespace View.custom_usercontrols
{
public partial class HintTextBox : TextBox
{
public static readonly DependencyProperty HintepDependencyProperty = DependencyProperty.Register("Hint", typeof(string), typeof(HintTextBox));
public string Hint
{
get
{
return (string)GetValue(HintepDependencyProperty);
}
set
{
SetValue(HintepDependencyProperty, value);
}
}
private string _text;
private bool _placeHolder;
public HintTextBox()
{
InitializeComponent();
if (Hint == null)
{
_text = "";
}
else
{
_text = Hint;
}
_placeHolder = true;
Text = _text;
Opacity = 0.2;
}
//extra code
}
}
This is my UserControl = ClickableControl
namespace View.custom_usercontrols
{
[ContentProperty(nameof(Children))]
public partial class ClickableControl : UserControl
{
public static readonly DependencyPropertyKey ChildrenProperty = DependencyProperty.RegisterReadOnly(
nameof(Children), // Prior to C# 6.0, replace nameof(Children) with "Children"
typeof(UIElementCollection),
typeof(ClickableControl),
new PropertyMetadata());
public static readonly DependencyProperty HoverColorDependencyProperty = DependencyProperty.Register("HoverColor", typeof(Brush), typeof(HintTextBox));
public static readonly DependencyProperty SelectedColorDependencyProperty = DependencyProperty.Register("SelectedColor", typeof(Brush), typeof(HintTextBox));
public static readonly DependencyProperty SelectedDependencyProperty = DependencyProperty.Register("Selected", typeof(Boolean), typeof(HintTextBox));
public Brush HoverColor
{
get
{
return (Brush)GetValue(HoverColorDependencyProperty);
}
set
{
SetValue(HoverColorDependencyProperty, value);
}
}
public Brush SelectedColor
{
get
{
return (Brush)GetValue(SelectedColorDependencyProperty);
}
set
{
SetValue(SelectedColorDependencyProperty, value);
}
}
private Brush BackgroundColor { get; set; }
public Boolean Selected
{
get
{
return (Boolean)GetValue(SelectedDependencyProperty);
}
set
{
SetValue(SelectedDependencyProperty, value);
if (value)
{
Background = SelectedColor;
}
else
{
Background = BackgroundColor;
}
}
}
public UIElementCollection Children
{
get { return (UIElementCollection) GetValue(ChildrenProperty.DependencyProperty); }
private set { SetValue(ChildrenProperty, value); }
}
public ClickableControl()
{
InitializeComponent();
Children = Grid.Children;
}
//EXTRA CODE
}
}
XAML:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:View"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:customUsercontrols="clr-namespace:View.custom_usercontrols"
//somewhere in the layout
<customUsercontrols:ClickableControl MouseDown="Search_OnMouseDown"
GotFocus="Search_OnGotFocus"
Background="#444444">
<StackPanel Orientation="Horizontal">
<materialDesign:PackIcon Kind="Magnify"
Margin="25 0 0 0"
Height="25"
Width="25"
Foreground="White"
VerticalAlignment="Center"/>
<customUsercontrols:HintTextBox x:Name="SearchT"
Padding="15"
Hint="SEARCH"
Width="204">
</customUsercontrols:HintTextBox>
</StackPanel>
</customUsercontrols:ClickableControl>
Thank you verry mutch
This is a bit late, but for anyone that views this question and still wonder about it, here goes:
Don't inherit from UserControl(Which inherits from contentControl) and then change default Content property of it, and expect it's content to be recognized upon call to InitializeComponent();
The elements "inside" the UserControl are its Content. if you defer its content to another property, stuff will go haywire.
Either you put the control you want to name under the UserControl xaml definition(the usual way), or you add it in code behind and name it,
or you can create a custom control and set its ControlTemplate with the control you want and specify it as a PART of the control:
http://paulstovell.com/blog/wpf-part-names
I have MainWindow and AddEdit UserControl. Inside MainWindow I render this AddEdit like <Views:AddEditData />, previous this namespace is added to Window element:
xmlns:Views="clr-namespace:MyProject.WPF.Views"
+++++++++++++++ ++++++++++++++++
ListOfData + + DataDetails +
+ + +
DataOne + + Name: txtBox1+
DataTwo + + +
DataThree + + +
+ + Save data +
+++++++++++++++ ++++++++++++++++
When user selects data on left side (DataTwo for example) I want to display it's properties (for simplicity only Name property) inside AddEdit user control (DataDetails panel).
Since this UserControl is stored separately from the MainWindow should I use same MainWindowViewModel and same datacontext or should I create separated ViewModel for AddEdit UserControl?
Hopefully this sounds clear, if not please ask for details.
Part 1. Display the properties of the control in MVVM
As I said in comments:
In MVVM ViewModel should not know about the controls, which are located. In such cases, use the attached behavior or leave the same side logic in View
ViewModel is not directly associated with a View, so just refer to the name of the control would not be right. It would be better to set a property in the Model, and bind it into View via ViewModel, but the property Name does not support Binding (quote from the MSDN):
Data binding a Name is technically possible, but is an extremely uncommon scenario because a data-bound Name cannot serve the main intended purpose of the property: to provide an identifier connection point for code-behind.
so I suggest to use the Tag property or Uid. In my example (give an below), I use Uid property for these purposes.
Part 2. Communication via ViewModels (pattern Mediator)
There are several embodiments of the Mediator pattern, but I like the most the implementation by XAML Guy, it is simple and clear - The Mediator Pattern.
Implementation code
public static class Mediator
{
static IDictionary<string, List<Action<object>>> pl_dict = new Dictionary<string, List<Action<object>>>();
static public void Register(string token, Action<object> callback)
{
if (!pl_dict.ContainsKey(token))
{
var list = new List<Action<object>>();
list.Add(callback);
pl_dict.Add(token, list);
}
else
{
bool found = false;
foreach (var item in pl_dict[token])
if (item.Method.ToString() == callback.Method.ToString())
found = true;
if (!found)
pl_dict[token].Add(callback);
}
}
static public void Unregister(string token, Action<object> callback)
{
if (pl_dict.ContainsKey(token))
{
pl_dict[token].Remove(callback);
}
}
static public void NotifyColleagues(string token, object args)
{
if (pl_dict.ContainsKey(token))
{
foreach (var callback in pl_dict[token])
callback(args);
}
}
}
To demonstrate his work, I created a small example, which consists of two Views, each has its own ViewModel and Model.
The project structure is shown below:
Output
When you click on Button, ListOfData ViewModel communicates via mediator with DataDetails ViewModel, thus:
Mediator.NotifyColleagues("ShowDetails", true);
Mediator.NotifyColleagues("SetSelectedFruit", ListOfDataModel.FruitGreen);
All procedures that interact with the properties must register their ViewModel like this:
private void ShowDetails_Mediator(object args)
{
bool showDetails = (bool)args;
if (showDetails == true)
{
DataDetailsModel.IsVisible = true;
}
else
{
DataDetailsModel.IsVisible = false;
}
}
private void SetSelectedFruit_Mediator(object args)
{
string selectedFruit = (string)args;
DataDetailsModel.SelectedFruit = selectedFruit;
}
public DataDetailsViewModel()
{
DataDetailsModel = new DataDetailsModel();
Mediator.Register("ShowDetails", ShowDetails_Mediator);
Mediator.Register("SetSelectedFruit", SetSelectedFruit_Mediator);
}
In the example I used a DataTemplate instead UserControl. Below are the main part of the project:
MainWindow.xaml
<Window x:Class="CommunicateWithVM.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ViewModels="clr-namespace:CommunicateWithVM.ViewModels"
Title="MainWindow"
WindowStartupLocation="CenterScreen"
Height="350"
Width="525">
<Grid>
<ContentControl Name="ListOfData"
ContentTemplate="{StaticResource ListOfDataView}">
<ViewModels:ListOfDataViewModel />
</ContentControl>
<ContentControl Name="DataDetails"
ContentTemplate="{StaticResource DataDetailsView}">
<ViewModels:DataDetailsViewModel />
</ContentControl>
</Grid>
</Window>
Models
DataDetailsModel
public class DataDetailsModel : NotificationObject
{
#region SelectedFruit
private string _selectedFruit = "";
public string SelectedFruit
{
get
{
return _selectedFruit;
}
set
{
_selectedFruit = value;
NotifyPropertyChanged("SelectedFruit");
}
}
#endregion
#region IsVisible
private bool _isVisible = false;
public bool IsVisible
{
get
{
return _isVisible;
}
set
{
_isVisible = value;
NotifyPropertyChanged("IsVisible");
}
}
#endregion
}
ListOfDataModel
public class ListOfDataModel : NotificationObject
{
#region FruitGreen
private string _fruitGreen = "Apple";
public string FruitGreen
{
get
{
return _fruitGreen;
}
set
{
_fruitGreen = value;
NotifyPropertyChanged("FruitGreen");
}
}
#endregion
#region FruitYellow
private string _fruitYellow = "Limon";
public string FruitYellow
{
get
{
return _fruitYellow;
}
set
{
_fruitYellow = value;
NotifyPropertyChanged("FruitYellow");
}
}
#endregion
}
ViewModels
DataDetailsViewModel
public class DataDetailsViewModel
{
#region DataDetailsModel
private DataDetailsModel _dataDetailsModel = null;
public DataDetailsModel DataDetailsModel
{
get
{
return _dataDetailsModel;
}
set
{
_dataDetailsModel = value;
}
}
#endregion
#region ShowDetails_Mediator
private void ShowDetails_Mediator(object args)
{
bool showDetails = (bool)args;
if (showDetails == true)
{
DataDetailsModel.IsVisible = true;
}
else
{
DataDetailsModel.IsVisible = false;
}
}
#endregion
#region SetSelectedFruit_Mediator
private void SetSelectedFruit_Mediator(object args)
{
string selectedFruit = (string)args;
DataDetailsModel.SelectedFruit = selectedFruit;
}
#endregion
#region DataDetailsViewModel Constructor
public DataDetailsViewModel()
{
DataDetailsModel = new DataDetailsModel();
Mediator.Register("ShowDetails", ShowDetails_Mediator);
Mediator.Register("SetSelectedFruit", SetSelectedFruit_Mediator);
}
#endregion
}
ListOfDataViewModel
public class ListOfDataViewModel
{
#region ListOfDataModel
private ListOfDataModel _listOfDataModel = null;
public ListOfDataModel ListOfDataModel
{
get
{
return _listOfDataModel;
}
set
{
_listOfDataModel = value;
}
}
#endregion
#region GreenButtonCommand
private ICommand _greenButtonCommand = null;
public ICommand GreenButtonCommand
{
get
{
if (_greenButtonCommand == null)
{
_greenButtonCommand = new RelayCommand(param => this.GreenButton(), null);
}
return _greenButtonCommand;
}
}
private void GreenButton()
{
Mediator.NotifyColleagues("ShowDetails", true);
Mediator.NotifyColleagues("SetSelectedFruit", ListOfDataModel.FruitGreen);
}
#endregion
#region YellowButtonCommand
private ICommand _yellowButtonCommand = null;
public ICommand YellowButtonCommand
{
get
{
if (_yellowButtonCommand == null)
{
_yellowButtonCommand = new RelayCommand(param => this.YellowButton(), null);
}
return _yellowButtonCommand;
}
}
private void YellowButton()
{
Mediator.NotifyColleagues("ShowDetails", true);
Mediator.NotifyColleagues("SetSelectedFruit", ListOfDataModel.FruitYellow);
}
#endregion
#region ListOfDataViewModel Constructor
public ListOfDataViewModel()
{
ListOfDataModel = new ListOfDataModel();
}
#endregion
}
Views
DataDetailsView
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ViewModels="clr-namespace:CommunicateWithVM.ViewModels">
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<DataTemplate x:Key="DataDetailsView" DataType="{x:Type ViewModels:DataDetailsViewModel}">
<StackPanel Width="200"
Background="AliceBlue"
HorizontalAlignment="Right"
Visibility="{Binding Path=DataDetailsModel.IsVisible,
Converter={StaticResource BooleanToVisibilityConverter}}">
<TextBlock Text="Fruit: " />
<TextBlock Text="{Binding Path=DataDetailsModel.SelectedFruit}" />
</StackPanel>
</DataTemplate>
</ResourceDictionary>
ListOfDataView
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ViewModels="clr-namespace:CommunicateWithVM.ViewModels">
<DataTemplate x:Key="ListOfDataView" DataType="{x:Type ViewModels:ListOfDataViewModel}">
<StackPanel Width="200"
Background="Azure"
HorizontalAlignment="Left">
<Button Uid="{Binding Path=ListOfDataModel.FruitGreen}"
Content="GreenButton"
Command="{Binding Path=GreenButtonCommand}" />
<Button Uid="{Binding Path=ListOfDataModel.FruitYellow}"
Content="YellowButton"
Command="{Binding Path=YellowButtonCommand}" />
</StackPanel>
</DataTemplate>
</ResourceDictionary>
This project is available at this link.
As UserControl is maintained separately and not a part of Window content. I would suggest to have separate ViewModel.
Benefits of having separate ViewModel:
Reusability - In future if you want to do some changes in data related to UserControl (may be some logic change), all you have to go to your ViewModel and update it and it will get reflected across all windows. You don't have to worry to go to each Window's view model and update code.
Testability - In case you want to test logic related to your control (data part me talking here not view part), you can write it in isolation. No need to worry about testing of Window view model code.
Loosely Coupled - More than one people can work in isolation. Say one developer have to update some code related to Main window and other have to update some code related to UserControl. With one ViewModel in place, there will be some overlap and they can't work in isolation since there are dependent on other person to do its work before he/she can plug in his/her code in ViewModel.
Also check out here for communication between different ViewModels as you might need that to communicate between Window view model and User Control View model to pass selected data in left window.
In my program I have tabItems that have their commands bound to a View Model. I am in the process of implementing a function that will copy the design structure of a "master" tabItem, along with it's command functionality in order to create a new tabItem. I need to do this because the user of this program will be allowed to add new tabItems.
Currently I am using the question Copying a TabItem with an MVVM structure, but I seem to be having trouble when the function tries to copy the Grid object using dependencyValue.
The class I am using:
public static class copyTabItems
{
public static IList<DependencyProperty> GetAllProperties(DependencyObject obj)
{
return (from PropertyDescriptor pd in TypeDescriptor.GetProperties(obj, new Attribute[] { new PropertyFilterAttribute(PropertyFilterOptions.SetValues) })
select DependencyPropertyDescriptor.FromProperty(pd)
into dpd
where dpd != null
select dpd.DependencyProperty).ToList();
}
public static void CopyPropertiesFrom(this FrameworkElement controlToSet,
FrameworkElement controlToCopy)
{
foreach (var dependencyValue in GetAllProperties(controlToCopy)
.Where((item) => !item.ReadOnly)
.ToDictionary(dependencyProperty => dependencyProperty, controlToCopy.GetValue))
{
controlToSet.SetValue(dependencyValue.Key, dependencyValue.Value);
}
}
}
When dependencyValue gets to {[Content, System.Windows.Controls.Grid]} the program throws an InvalidOperationException was Unhandled stating that, "Specified element is already the logical child of another element. Disconnect it first".
What does this mean? Is this a common problem with the Grid in WPF (am I breaking some rule by trying to do this?)? Is there something in my program that I am not aware of that is causing this?
Ok. This is how you're supposed to deal with a TabControl in WPF:
<Window x:Class="MiscSamples.MVVMTabControlSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MiscSamples"
Title="MVVMTabControlSample" Height="300" Width="300">
<Window.Resources>
<DataTemplate DataType="{x:Type local:Tab1ViewModel}">
<!-- Here I just put UI elements and DataBinding -->
<!-- You may want to encapsulate these into separate UserControls or something -->
<StackPanel>
<TextBlock Text="This is Tab1ViewModel!!"/>
<TextBlock Text="Text1:"/>
<TextBox Text="{Binding Text1}"/>
<TextBlock Text="Text2:"/>
<TextBox Text="{Binding Text2}"/>
<CheckBox IsChecked="{Binding MyBoolean}"/>
<Button Command="{Binding MyCommand}" Content="My Command!"/>
</StackPanel>
</DataTemplate>
<!-- Here you would add additional DataTemplates for each different Tab type (where UI and logic is different from Tab 1) -->
</Window.Resources>
<DockPanel>
<Button Command="{Binding AddNewTabCommand}" Content="AddNewTab"
DockPanel.Dock="Bottom"/>
<TabControl ItemsSource="{Binding Tabs}"
SelectedItem="{Binding SelectedTab}"
DisplayMemberPath="Title">
</TabControl>
</DockPanel>
</Window>
Code Behind:
public partial class MVVMTabControlSample : Window
{
public MVVMTabControlSample()
{
InitializeComponent();
DataContext = new MVVMTabControlViewModel();
}
}
Main ViewModel:
public class MVVMTabControlViewModel: PropertyChangedBase
{
public ObservableCollection<MVVMTabItemViewModel> Tabs { get; set; }
private MVVMTabItemViewModel _selectedTab;
public MVVMTabItemViewModel SelectedTab
{
get { return _selectedTab; }
set
{
_selectedTab = value;
OnPropertyChanged("SelectedTab");
}
}
public Command AddNewTabCommand { get; set; }
public MVVMTabControlViewModel()
{
Tabs = new ObservableCollection<MVVMTabItemViewModel>();
AddNewTabCommand = new Command(AddNewTab);
}
private void AddNewTab()
{
//Here I just create a new instance of TabViewModel
//If you want to copy the **Data** from a previous tab or something you need to
//copy the property values from the previously selected ViewModel or whatever.
var newtab = new Tab1ViewModel {Title = "Tab #" + (Tabs.Count + 1)};
Tabs.Add(newtab);
SelectedTab = newtab;
}
}
Abstract TabItem ViewModel (you to derive from this to create each different Tab "Widget")
public abstract class MVVMTabItemViewModel: PropertyChangedBase
{
public string Title { get; set; }
//Here you may want to add additional properties and logic common to ALL tab types.
}
TabItem 1 ViewModel:
public class Tab1ViewModel: MVVMTabItemViewModel
{
private string _text1;
private string _text2;
private bool _myBoolean;
public Tab1ViewModel()
{
MyCommand = new Command(MyMethod);
}
public string Text1
{
get { return _text1; }
set
{
_text1 = value;
OnPropertyChanged("Text1");
}
}
public bool MyBoolean
{
get { return _myBoolean; }
set
{
_myBoolean = value;
MyCommand.IsEnabled = !value;
}
}
public string Text2
{
get { return _text2; }
set
{
_text2 = value;
OnPropertyChanged("Text2");
}
}
public Command MyCommand { get; set; }
private void MyMethod()
{
Text1 = Text2;
}
}
Edit: I forgot to post the Command class (though you surely have your own)
public class Command : ICommand
{
public Action Action { get; set; }
public void Execute(object parameter)
{
if (Action != null)
Action();
}
public bool CanExecute(object parameter)
{
return IsEnabled;
}
private bool _isEnabled = true;
public bool IsEnabled
{
get { return _isEnabled; }
set
{
_isEnabled = value;
if (CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
}
public event EventHandler CanExecuteChanged;
public Command(Action action)
{
Action = action;
}
}
And finally PropertyChangedBase (just a helper class)
public class PropertyChangedBase:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Result:
Basically, each Tab Item type is a Widget, which contains its own logic and Data.
You define all logic and data at the ViewModel or Model level, and never at the UI level.
You manipulate the data defined in either the ViewModel or the Model level, and have the UI updated via DataBinding, never touching the UI directly.
Notice How I'm leveraging DataTemplates in order to provide a specific UI for each Tab Item ViewModel class.
When copying a new Tab, you just create a new instance of the desired ViewModel, and add it to the ObservableCollection. WPF's DataBinding automatically updates the UI based on the Collection's change notification.
If you want to create additional tab types, just derive from MVVMTabItemViewModel and add your logic and data there. Then, you create a DataTemplate for that new ViewModel and WPF takes care of the rest.
You never, ever, ever manipulate UI elements in procedural code in WPF, unless there's a REAL reason to do so. You don't "uncheck" or "disable" UI Elements because UI elements MUST reflect the STATE of the data which is provided by the ViewModel. So a "Check/Uncheck" state or an "Enabled/Disabled" state is just a bool property in the ViewModel to which the UI binds.
Notice how this completely removes the need for horrendous winforms-like hacks and also removes the need for VisualTreeHelper.ComplicateMyCode() kind of things.
Copy and paste my code in a File -> New Project -> WPF Application and see the results for yourself.