I want to use MVVM in my WPF application. I currently have a Model and a view which has DataGrid and some other controls. I created a ViewModel based on my model and don't know if I did it correctly. The view is just a simple dialog box. I want to fill the DataGrid view.
How can I tell the DataGrid to bind with the ViewModel?
I would like to bind properties(inside viewmodel like ID and Date) to the datagrid.
SO like if there is two objects inside the list I would like to see two rows in datagrid with the specific ID's and Date's.
Im setting the datacontext inside the class instead xaml.
Here is the code so far:
public class ViewModel : INotifyPropertyChanged
{
private string _id;
private DateTime _date;
private ObservableCollection<Object> _list;
public string Id
{
get { return _id; }
set
{
_id = value;
PropertChanged("Id");
}
}
public DateTime Date
{
get { return _date; }
set
{
_date = value;
PropertChanged("Date");
}
}
public ObservableCollection<Object> list
{
get { return _list; }
set
{
_list = value;
PropertChanged("list");
}
}
public LicenseViewModel()
{
list = GetList();
}
public event PropertyChangedEventHandler PropertyChanged;
public void PropertChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
And the XAML:
<Window x:Class="Import"
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:Controls="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
mc:Ignorable="d"
ResizeMode="CanResizeWithGrip"
x:Name="ImportLicense"
d:DesignHeight="493" d:DesignWidth="559"
Title="Import Licenses" SizeToContent="WidthAndHeight">
<Grid Width="538">
<DataGrid x:Name="Imported" VerticalAlignment="Top" AutoGenerateColumns="False" CanUserResizeColumns="True">
<DataGrid.Columns>
<DataGridTextColumn Header="Entitlement ID" Binding="{Binding Path=ID}"/>
<DataGridTextColumn Header="Date Sold" Binding="{Binding Path=Date}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
You need to set the data context for the DataGrid to the instance of your view model. You can do this by simply setting the DataContext of your View or the DataGrid to your instance of your view model in the constructor of the view class. This is a quick and dirty way of doing this.
If you want to be more sophisticated you can create a DepenencyProperty on your view class like this:
public static DependencyProperty ViewModelProperty =
DependencyProperty.Register("ViewModel",
typeof(ItemViewModel),
typeof(ViewClassHere));
public ItemViewModel ViewModel
{
get { return (ItemViewModel)base.GetValue(ItemViewModel); }
set { base.SetValue(ItemViewModel, value); }
}
Then you'd bind to that property in any one of many ways but one way would be like:
<DataGrid ItemsSource="{Binding ElementName=windowName, Path=viewName.list}">
There are a bunch of ways to do this, these are just two possible ways to do this.
the common way to display data with a datagrid is to set the itemssource
<DataGrid ItemsSource="{Binding MyCollection}"/>
your viewmodel defines 2properties and one collection, but in your xaml you bind your properties to the datagrid columns and don't set any itemssource.
its not clear to me what you would like to see in your datagrid, but your 2 properties ID and DateTime are not part of any collection, so why you want this to display in your datagrid?
please edit your question and give some information of what you wanna see in your datagrid.
Try like this:
<window.Resources>
<ViewModel x:Key="ViewModel"></ViewModel >
</window.Resources>
<Grid x:Name="ValueDetail" DataContext="{StaticResource ViewModel}">
<DataGrid ItemsSource="{Binding MyCollection}"/>
</Grid>
Related
EDIT : Question was not clear enough. In fact there are two of them.
Q1 :
I have a UserControl "CustomView" that is dynamically created with a template:
<Window.Resources>
<DataTemplate DataType="{x:Type my:CustomViewModel}">
<my:CustomView/>
</DataTemplate>
</Window.Resources>
<ItemsControl ItemsSource="{Binding Path=CustomList}"/>
Where CustomList is a Property of type ObservableCollection<'CustomViewModel> belonging to MainWindowViewModel, which is the Window's DataContext.
In CustomView's Xaml code, there are some Properties binded to CustomViewModel's Properties. Everything works properly. But when I try to do this in CustomView's code behind :
public CustomView()
{
InitializeComponents();
if (this.DataContext == null) Console.WriteLine ("DataContext is null");
else Console.WriteLine(this.DataContext.GetType().ToString());
}
It is written in Console : 'DataContext is null', even if bindings are working betweeen CustomView and CustomViewModel. Do you know why it's working?
Q2 :
Now, imagine that CustomView has another UserControl (IndexPicker) inside of it. IndexPicker has an associated ViewModel too (IndexPickerViewModel) who's in charge with data access. I need to bind one property ("Index") of this IndexPickerViewModel to the previous CustomViewModel's property "Id". I want to instantiate it in StaticResources and bind it to the CustomViewModel (which I believe is the dataContext according to my previous question):
<UserControl x:Class="MyView.CustomView"
...
<UserControl.Resources>
<DataTemplate DataType="{x:Type myPicker:IndexPickerViewModel}">
<myPicker:IndexPicker/>
</DataTemplate>
<myPicker:IndexPickerViewModel x:Key="pickerViewModel" Index="{Binding Path=Id}/>
</Window.Resources/>
<ContentControl Content={StaticResource pickerViewModel}/>
What I have tried : I tried to make "IndexPickerViewModel" inherit from "DependencyObject" and make "Index" a DependencyProperty. But the following error message shows up :
"System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Id; DataItem=null; target element is 'IndexPickerViewModel' (HashCode=59604175); target property is 'Index' (type 'Nullable`1')
I believe this is because of what I asked just above. But is it possible to do something like that? If yes, what am I missing? And : Is this a stupid idea?
Thank you in advance for any help.
Now, imagine that CustomView has another UserControl (IndexPicker) inside of it. IndexPicker has an associated ViewModel too (IndexPickerViewModel) who's in charge with data access. I need to bind one property ("Index") of this IndexPickerViewModel to the previous CustomViewModel's property "Id". I want to instantiate it in StaticResources and bind it to the CustomViewModel (which I believe is the dataContext according to my previous question)
If IndexPicker doesn't have an explicitly set datacontext then IndexPicker will inherit the datacontext from it's parent element.
However if IndexPicker does already have a datacontext then you will have to use relative source binding with an ancestor search:
Index="{Binding Id, RelaticeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, FallbackValue={x:Null}}"
Of course you can probably already sense that this is messy. Going after standard properties of a UIElement or Control is quite safe (and common), but when you start going after custom properties then you are introducing dependencies between the child control and its parent (when the child control shouldn't know much of anything about its parent), and you are also bound to start getting binding errors at some stage (hence the use of a fallback value).
It seems that I've asked too early because I've found answers by myself.
Answer to Question1
When you have a UserControl that is dynamically created from a DataTemplate in which it is associated with another object (belonging to a ViewModel or to a Resource), this object is defined as the DataContext of the UserControl. However, you cannot reach it in the UserControl's constructor, you have to wait until the "Loaded" event is raised :
public CustomUserControl()
{
InitializeComponent();
Console.WriteLine(this.DataContext.ToString());
// This doesn't work : DataContext is null
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
Console.WriteLine(this.DataContext.ToString());
// or
Console.WriteLine((sender as UserControl).DataContext.ToString());
// this is Ok.
}
Answer to Question2
This is how you do to get a UserControl whose ViewModel is instantiated in a parent UserControl.Resources :
You don't do it.
Instead, you instantiate its ViewModel in its parent ViewModel. Full example :
MainWindow.xaml:
<Window x:Class="MainWindow"
...
xmlns:local="clr-namespace:my_project_namespace"
xmlns:cust="clr-namespace:CustomUserControl;assembly=CustomUserControl"
...>
<Window.Resources>
<DataTemplate DataType="{x:Type cust:CustomControlViewModel}">
<cust:CustomControlView>
</DataTemplate>
<!-- Here are listed all the types inheriting from CustomControlViewModel and CustomControlView.-->
<!-- CustomControlViewModel and CustomControlView are used as "abstract" classes-->
</Window.Resources>
<Window.DataContext>
<local:MainWindowViewModel>
</Window.DataContext>
<Grid>
<ItemsControl ItemsSource="{Binding Path=CustomVMList}"/>
</Grid>
</Window>
MainWindowViewModel.cs:
namespace my_project_namespace
{
public class MainWindowViewModel
{
public ObservableCollection<CustomControlViewModel> CustomVMList { get; set; }
public MainWindowViewModel()
{
CustomVMList = new ObservableCollection<CustomControlViewModel>();
// Fill in the list...
}
}
}
CustomControlView.xaml
<UserControl x:class="CustomUserControl.CustomControlView"
...
xmlns:my="clr-namespace:IndexPicker;assembly=IndexPicker"
...>
<UserControl.Resources>
<DataTemplate DataType="{x:Type my:IndexPickerViewModel}">
<my:IndexPickerView/>
</DataTemplate>
</UserControl.Resources>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Name}/>
<ContentControl Content="{Binding Path=MyIndexPicker}"/>
</Grid>
</UserControl>
And this is where it's interesting :
CustomControlViewModel.cs:
namespace CustomUserControl
{
public class CustomControlViewModel : INotifyPropertyChanged
{
public IndexPickerViewModel MyIndexPicker{ get; set; }
public string Name { get ; set; }
public int Id
{
get
{
return MyIndexPicker.Index;
}
set
{
if (value != MyIndexPicker.Index)
{
MyIndexPicker.Index = value;
NotifyPropertyChanged("Id");
}
}
}
public CustomControlViewModel(string _name)
{
Name = _name;
MyIndexPicker = new IndexPickerViewModel();
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName);
}
}
}
IndexPickerView.xaml:
<UserControl x:Class="IndexPicker.IndexPickerView"
...
...>
<Grid>
<Combobox ItemsSource="{Binding Path=MyTable}"
DisplayMemberPath="ColumnXYZ"
SelectedItem={Binding Path=SelectedRow}/>
</Grid>
</UserControl>
Finally
IndexPickerViewModel.cs:
namespace IndexPicker
{
public class IndexPickerViewModel : INotifyPropertyChanged
{
private DataAccess data;
public DataView MyTable { get; set; }
private DataRowView selectedRow;
public DataRowView SelectedRow
{
get { return selectedRow; }
set
{
selectedRow = value;
NotifyPropertyChanged("SelectedRow");
}
}
public int? Index
{
get
{
if (SelectedRow != null) return (int?)selectedRow.Row["Column_Id"];
else return null;
}
set
{
SelectedRow = MyTable[MyTable.Find((int)value)];
NotifyPropertyChanged("Index");
}
}
public IndexPickerViewModel()
{
data = new DataAccess();
MyTable = data.GetTableView("tableName");
MyTable.Sort = "Column_Id";
}
// And don't forget INotifyPropertyChanged implementation
}
}
This configuration is used with several different UserControls inheriting from CustomControlView and their ViewModel inheriting from CustomControlViewModel. They are dynamically created and listed in CustomVMList. Here CustomControlViewModel containing an IndexPicker is already a specialization.
Concrete use: Generic Dialog for CRUD database Tables, which can dynamically create UserControls depending on each Table Columns. The specialization shown here is used in case of a column containing a foreign key.
I hope its clear.
The code listed above may contain mistakes. Criticisms and remarks are welcome.
I have working implementation of datagrid grouping. Below is what i do (GroupStyle with expander omitted):
<CollectionViewSource x:Key="SelectedObjectsViewSource" Source="{Binding SelectedObjectItems}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="TableId"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
<DataGrid Name="SelectedObjectsGrid"
ItemsSource="{Binding Source={StaticResource SelectedObjectsViewSource}}"
SelectionMode="Extended"
CanUserAddRows="False"
AutoGenerateColumns="False">
I would like to add a checkbox that user can turn off/on grouping. But i have no idea how to implement this in MVVM
I advise you to bind the checkbox to a bool property of the viewmodel where its setter also sets the grouping status of the collectionview following the assigned value. Like in the following sample: where the bool property bound to the checkbox status is GroupView and the collection bound to the datagrid is View.
C# ViewModel
class ViewModel : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
private ICollectionView _View;
public ICollectionView View
{
get
{
return _View;
}
set
{
_View = View;
NotifyPropertyChanged("View");
}
}
private bool _GroupView;
public bool GroupView
{
get
{
return _GroupView;
}
set
{
if (value != _GroupView)
{
// Clear Grouping status of the view
View.GroupDescriptions.Clear();
if (value)
{
// If true set Grouping status
View.GroupDescriptions.Add(new PropertyGroupDescription("TableId"));
}
_GroupView = value;
NotifyPropertyChanged("GroupView");
// Notify the UI that also the View changed in order to redraw the datagrid with or without grouping
NotifyPropertyChanged("View");
}
}
}
}
C# Code Behind
public partial class MyWindow : Window
{
public MyWindow()
{
InitializeComponent();
ViewModel myViewModel = new ViewModel();
myViewModel.View = .....;
DataContext = myViewModel;
}
}
XAML
<StackPanel>
<CheckBox IsChecked="{Binding GroupView, Mode=TwoWay}"/>
<DataGrid Name="SelectedObjectsGrid"
ItemsSource="{Binding View, Mode=TwoWay}"
SelectionMode="Extended"
CanUserAddRows="False"
AutoGenerateColumns="False"/>
</StackPanel>
You can create another DataGrid in current View:
<DataGrid Name="SelectedObjectsGridWithoutGrouping" Visibility="False"
ItemsSource="{Binding NewCollection}"
SelectionMode="Extended"
CanUserAddRows="False"
AutoGenerateColumns="False">
After that, you must create NewCollection in ViewModel (which contains your items from SelectedObjectItems collection, but without grouping) and when user changes the checkbox, showing or hiding one of them by changing Visibility SelectedObjectsGrid or SelectedObjectsGridWithoutGrouping.
This should be an extremely simple solution, but searching through the internet there seems to be multiple different ways to do binding and NONE seem to actually work.
I've created a simple application with a button, textbox and listbox. The user adds text to the textbox, clicks Add and I want the text to appear in the list box. Note that the Add button will create a Person with the firstname the text in the textbox and the last name "Jones". This is just to figure out how to get binding to actually work. I have the ObservableCollection but can't seem to even figure out how to put in the resource to the object within the class itself. Is this even possible? do I have to create a separate class to have a binding?
Here is the complete XMAL
<UserControl x:Class="simpleBinding.MainPage"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:z="clr-namespace:simpleBinding"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Canvas x:Name="LayoutRoot" Background="White">
<Button Name="_b" Content="Add" Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" Width="58" Canvas.Left="90" Canvas.Top="5" Click="OnAdd" />
<TextBox Name="_tb" Canvas.Left="12" Canvas.Top="4" Height="24" Width="72"></TextBox>
<ListBox Name="_list" Canvas.Left="18" Canvas.Top="41" Height="98" Width="190" />
</Canvas>
and here is the complete Code behind
namespace simpleBinding
{
public partial class MainPage : UserControl
{
public ObservableCollection<Person> PersonList = new ObservableCollection<Person> ();
public MainPage()
{
InitializeComponent();
}
private void OnAdd(object sender, RoutedEventArgs e)
{
PersonList.Add(new Person(_tb.Text, "Jones"));
}
}
public class Person
{
public string FirstName {private set; get;}
public string LastName {private set; get; }
public Person(string fName, string lName)
{
FirstName = fName;
LastName = lName;
}
}
}
thanks for any help,
chris
To illustrate Ravuthasamy's & aqwert's comments. You have to set a DataContext first. You can set this in DataContext or read how MVVM work (It's a good Silvelight binding pattern) :
c#
public MainPage()
{
InitializeComponent();
DataContext = this;
}
After you can bind the class properties to elements :
Xaml
<ListBox
ItemsSource="{Binding PersonList}"
Canvas.Left="18"
Canvas.Top="41"
Height="98"
Width="190" />
Following the timeline you can see that this has taken me a week to finally get to a solution. I post it here now in hopes that someone else won't waste this much time. There seems to be a lot of posts about how to deal with this issue and the examples are limited. They either show only C# or Xaml. Then CollectionChanged and PropertyChanged aren't dealt with in a single example.
This is a simple example, that implements both collection changed and property changed. As well as binding in Xaml
Here is the Xaml.
<UserControl x:Class="simpleBinding.MainPage"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:src="clr-namespace:simpleBinding"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Canvas x:Name="LayoutRoot" Background="White" DataContext="{Binding}">
<Canvas.Resources>
<src:PersonList x:Key="myDataSource"></src:PersonList>
</Canvas.Resources>
<Button Name="_b" Content="Add" Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" Width="58" Canvas.Left="90" Canvas.Top="5" Click="OnAdd" />
<Button Canvas.Left="150" Canvas.Top="5" Content="Edit" Height="23" Name="button1" Width="58" Click="OnEdit" />
<TextBox Name="_tb" Canvas.Left="12" Canvas.Top="4" Height="24" Width="72"></TextBox>
<ListBox Name="_list" Canvas.Left="18" Canvas.Top="41" Height="98" Width="190" ItemsSource="{Binding Source={StaticResource myDataSource}}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=FirstName}" Margin="0,0,2,0" />
<TextBlock Text="{Binding Path=LastName}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Canvas>
Add a xmlns that will reference your code behind. In this case my namespace is xmlns:src then you can use VS intellisense to go to the correct class.
Add a resource to the layoutRoot item. In my case I'm using a canvas, but it could be Grid or Stackpanel etc.
With the resource declared, you can now set the ItemSource binding in the ListBox.
I've chosen to use a template to display the data which I think is really cool (best part of Xaml!) In this case there are two textBlocks but if my underlying data source had an image, I could have used this was well to graphically display the data. The binding for each textbox can be set because the exposed properties of the object are declared in the C# code. Which will be discussed next
C# Code behind
namespace simpleBinding
{
public partial class MainPage : UserControl
{
public PersonList m_pList = new PersonList();
public MainPage()
{
InitializeComponent();
_list.ItemsSource = m_pList;
m_pList.Add(new Person("John", "Doe"));
}
private void OnAdd(object sender, RoutedEventArgs e)
{
m_pList.Add(new Person("Jones", _tb.Text));
}
private void OnEdit(object sender, RoutedEventArgs e)
{
m_pList[1].FirstName = _tb.Text;
}
}
public class PersonList : ObservableCollection<Person> , INotifyPropertyChanged
{
public PersonList() : base() // need to call base on intialization otherwise the binded resource is not updated.
{
Add(new Person("Willa", "Cather"));
Add(new Person("Isak", "Dinesen"));
Add(new Person("Victor", "Hugo"));
Add(new Person("Jules", "Verne"));
}
}
public class Person : INotifyPropertyChanged
{
private string _fName;
private string _lName;
public event PropertyChangedEventHandler PropertyChanged;
public string FirstName
{
set
{
_fName = value;
NotifyPropertyChanged("FirstName");
}
get
{
return _fName;
}
}
public string LastName
{
set
{
_lName = value;
NotifyPropertyChanged("LastName");
}
get
{
return _lName;
}
}
public Person(string fName, string lName) : base()
{
FirstName = fName;
LastName = lName;
}
public override string ToString()
{
return String.Format("{0} {1}", FirstName, LastName);
}
private void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
I've chosen to use the ObservableCollection because it implements INotifyCollectionChanged. The public variable is exposed which allows you to bind to the resource declared in the Xaml. (Better code, make the var private and have a property that exposes the variable through a get!)
The ListBox _List needs to have its ItemsSource property set in Code Behind!!! without this whenever you change the list (add, delete etc) the UI is not updated. AND in fact you do not need the binding in the ListBox at all because we set the source in Code behind it is nice however in that in the designer with this bound control you can see that the binding is working because there are four names added when instantiating the PersonList.
The ObservableCollection needs to have the INotifyCollectionChanged added. Without this, when a property is changed the UI is NOT changed.
The properties that are to be exposed to the UI need to be implement in the object that is contained within the ObservableCollection (in my case the class Person exposed both FirstName and LastName) and then these properties can be bound in the Xaml (see the textBlocks's)
INotifyPropertyChanged requires that you implement a PropertyChanged event i.e. public event PropertyChangedEventHandler PropertyChanged;
To actually fire that event the "Person" object needs to implement code to do that, which in my case is the NotifyPropertyChanged Method. Each time a property is set, I call this method, which in turn looks to see is the PropertyChanged event is not null, and if not, then it raises that event.
Here is the key to property changes, without adding the , INotifyPropertyChanged to the Observable collection PropertyChanged is null.
Hope this helps someone
Please help me to figure out how to work with ComboBoxColumn in WPF's DataGrid.
I'm trying to create a list of devices, where each device have dynamic list of states in field "log".
<DataGrid AutoGenerateColumns="False" Margin="12,6,12,12" Name="dataGrid1" Grid.Row="1" SelectionUnit="FullRow">
<DataGrid.Columns>
...
<DataGridComboBoxColumn Header="Log"
ItemsSource="{Binding log, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:Device}}}"/>
</DataGrid.Columns>
</DataGrid>
public partial class MainWindow : Window
{
public ObservableCollection<Device> devices;
...
}
public MainWindow()
{
...
dataGrid1.ItemSource = devices;
}
public class Device : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public Device() {log = new ObservableCollection<string>();}
...
private ObservableCollection<string> _log;
public ObservableCollection<string> log { get { return _log; }
set { _log = value; OnPropertyChanged("log"); } }
}
Can you share any suggestions: How can i show in each combobox in datagrid list "log" of each object?
MSDN: DataGridComboboxColumns says:
To populate the drop-down list, first set the ItemsSource property for
the ComboBox by using one of the following options:
A static resource. For more information, see StaticResource Markup Extension.
An x:Static code entity. For more information, see x:Static Markup Extension.
An inline collection of ComboBoxItem types.
So basically to just bind to data object`s collection property it`s better to use DataGridTemplateColumn:
<DataGridTemplateColumn Header="Log">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding log}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
This type of column gives you some more posibilities for templating too.
I have an UserControl(AutoComplete) with his own ViewModel. When I use the UserControl inside a window, it run well, connect to a service, and paint data correctly.
The UserControl datacontext is set via xaml, and is binded to a property of the main window viewModel.
Ok, now I want that the UserControl can load data from the main window view model. The thing is that, supposing the usercontrol loads countries. When I type in the Usercontrol it returns the list of countries and when I select one of them, i.e. "Spain", the SelectedItem property of the Usercontrols updates to "Spain". I want an object in main window viewModel to udate to "Spain" and vice-versa, if I update the country object in the main window viewmodel, the selecteditem of the user should update too.
How can I accomplish that
I have this in my mainview:
<amctrls:AmAutoCompleteView DataContext="{Binding controladorAutoCompleteCountry}" />
the user control loks like this:
<telerik:RadComboBox Margin="2,0,0,0" Grid.Row="0" Grid.Column="0"
IsEditable="True"
Name="RadCbo"
ItemsSource="{Binding objectList}"
DisplayMemberPath="{Binding fieldToShow}"
OpenDropDownOnFocus="True"
SelectedItem="{Binding selectedCountry, Mode=TwoWay}"
Text="{Binding searchText, Mode=TwoWay}"
IsTextSearchEnabled="False"
StaysOpenOnEdit="True" />
controladorAutoCompleteCountry is a property of my mainview wih is an instance of the usercontrol viewmodel.
The viewmodel of the main view manage addresses, and what I want is to bind an address country to the usercontrol in order to edit the address. If i have the usercontrol binded to an instance of its controller, how can I bind the Country object of the address?
If you need to make those 2 views independent which is good if you want to reuse your control, go with Event Aggregator or simple events. Whenever an item is selected in the user control, it will publish an event stating, something interesting has happened. Main viewmodel can subscribe to those events and do the required. A simple case would be a creating a static class with an event and RaiseEvent method, user control will RaiseEvent and main viewmodel with be subscribing the event. Data to be passed between them can be added to the event args.
It's a bit the other way around, but you can try something like this:
Have a MainView with a
combobox that is bound to the string property SelectedCountry and method ChangeCountry()
ContentControl that is bound to CountryInfoViewModel property SelectedCountryControl
You can now bind your combobox to the CountryInfoViewModel that is loaded in your MainView.
Below is an example that worked for me (note that I used caliburn micro here).
It basicly updates the CountryInfoViewModel/View when a different country has been selected.
You could improve the ChangeCountry method to get all the data, and of course improve the CountryInfoViewModel/View to show everything you want shown.
MainViewModel
class MainViewModel : Screen
{
#region fields
private BindableCollection<string> _listOfCountries;
private string _selectedCountry;
private CountryInfoViewModel _selectedCountryControl;
#endregion fields
#region properties
public BindableCollection<string> ListOfCountries
{
get
{
return new BindableCollection<string>
{
"France",
"Holland",
"Russia"
};
}
}
public string SelectedCountry
{
get { return _selectedCountry; }
set
{
_selectedCountry = value;
NotifyOfPropertyChange(() => SelectedCountry);
}
}
public CountryInfoViewModel SelectedCountryControl
{
get { return _selectedCountryControl; }
set
{
_selectedCountryControl = value;
NotifyOfPropertyChange(() => SelectedCountryControl);
}
}
#endregion properties
public MainViewModel()
{
SelectedCountry = "Holland";
ChangeCountry();
}
public void ChangeCountry()
{
SelectedCountryControl = new CountryInfoViewModel()
{
CountryName = SelectedCountry
};
}
}
MainView:
<UserControl x:Class="WpfModifyDifferentView.Views.MainView"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel>
<ComboBox x:Name="ChangeCountry" SelectedItem="{Binding SelectedCountry}" ItemsSource="{Binding ListOfCountries}"/>
<ContentControl x:Name="SelectedCountryControl"/>
</StackPanel>
</UserControl>
CountryInfoViewModel:
class CountryInfoViewModel : Screen
{
#region fields
private string _countryName;
#endregion fields
#region properties
public string CountryName
{
get { return _countryName; }
set
{
_countryName = value;
NotifyOfPropertyChange(() => CountryName);
}
}
#endregion properties
}
CountryInfoView:
<UserControl x:Class="WpfModifyDifferentView.Views.CountryInfoView"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel Orientation="Vertical">
<TextBlock Text="You have chosen the country:"/>
<TextBlock x:Name="CountryName"/>
</StackPanel>
</UserControl>