I have 2 viewmodels that inherit from the same BaseViewModel, which has an ObservableCollection as a public property.
The first viewmodel shows the ObservableCollection, while the second viewmodel allows for updating the collection.
How come the first view doesn't see the updated collection?
public class BaseViewModel : INotifyPropertyChanged
{
private Playlist _currentPlaylist;
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public Playlist CurrentPlaylist
{
get
{
if (_currentPlaylist == null)
{
_currentPlaylist = _library.CurrentPlaylist;
}
return _currentPlaylist;
}
set
{
_currentPlaylist = value;
NotifyPropertyChanged("CurrentPlaylist");
}
}
public BaseViewModel()
{
_library = new Library();
_dbContext = new MusicTrackerDataContext();
}
}
The first view that uses the inherited BaseViewModel uses CurrentPlaylist databound.
The second view sets the CurrentPlaylist again:
public class ArtistPageViewModel : BaseViewModel
{
public void PlaylistBtn_Clicked(ListView albumListView)
{
Library.AddSelectionToCurrentPlaylist(albumListView.SelectedItems.Cast<Album>());
CurrentPlaylist = Library.CurrentPlaylist;
}
}
Seeing that my BaseViewModel raises the INotifyPropertyChanged event when I set my CurrentPlaylist, I'd expect that the listview to which my CurrentPlaylist is bound, is updated.
What am I doing wrong?
Edit
The code for the View that's showing the old collection
public sealed partial class HubPage : Page
{
private HubPageViewModel _hubPageViewModel;
public HubPageViewModel HubPageViewModel
{
get
{
return _hubPageViewModel;
}
}
}
The XAML code for my HubPageViewModel
<Page
x:Class="MyProject.HubPage"
DataContext="{Binding HubPageViewModel, RelativeSource={RelativeSource Self}}"
mc:Ignorable="d">
<HubSection x:Uid="HubSection5" Header="Now Playing"
DataContext="{Binding CurrentPlaylist}" HeaderTemplate="{ThemeResource HubSectionHeaderTemplate}">
<DataTemplate>
<ListView
SelectionMode="None"
IsItemClickEnabled="True"
ItemsSource="{Binding Tracks}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Title}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DataTemplate>
</HubSection>
</HubSection>
Edit 2
I've changed my code to the following (according to the comments)
public sealed partial class HubPage : Page
{
private readonly NavigationHelper navigationHelper;
private static HubPageViewModel _hubPageViewModel; // Made it static
public HubPageViewModel HubPageViewModel
{
get
{
return _hubPageViewModel;
}
}
}
<Page
x:Class="MyProject.HubPage"
DataContext="{Binding HubPageViewModel, RelativeSource={RelativeSource Self}}"
xmlns:vm="using:MyProject.ViewModels" // Added reference to my VM
mc:Ignorable="d">
<ResourceDictionary>
<vm:HubPageViewModel x:Name="hubPageViewModel"/> // Added the key
</ResourceDictionary>
<HubSection x:Uid="HubSection5" Header="Now Playing"
DataContext="{Binding Source={StaticResource hubPageViewModel}}" HeaderTemplate="{ThemeResource HubSectionHeaderTemplate}">
<DataTemplate>
<ListView
SelectionMode="None"
IsItemClickEnabled="True"
ItemsSource="{Binding CurrentPlaylist.Tracks}"
ItemClick="ItemView_ItemClick">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,27.5" Holding="StackPanel_Holding">
<TextBlock Text="{Binding Title}" Style="{ThemeResource ListViewItemTextBlockStyle}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DataTemplate>
</HubSection>
But it's still not updated when I return from my second viewmodel.
Even though both view models inherit the same base class, the state of the base class is not shared between the two view models. That is, HubPageViewModel and ArtistPageViewModel do not share the same instance of Playlist. They are completely different properties.
Since both view models points to the same playlist instance and that instance is an ObservableCollection, all changes to that instance of ObservableCollection will be shared between the two view models because both views are bound to the "collection changed" notifications for the instance they are watching. In your example, ArtistPageViewModel.PlaylistBtn_Clicked does not changes the data within the ObservableCollection, it changes the collection itself. This changes the collection that the second view is watching but does not change the one of the first view.
Related
So I just setup a project and added a custom UserControl that looks like this.
<Grid>
<ItemsControl ItemsSource="{Binding UserViewModel.Users}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<controls:UserCard/>
<TextBlock Text="{Binding Name}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
As you can see I tried binding the Text property buti it doesn't bind.
Now there could be a lot of reasons to why it's behaving like this so I will try to narrow it down.
I've created a BaseViewModel that will hold my ViewModels and it looks like this.
public class BaseViewModel : ObservableObject
{
public UserViewModel UserViewModel { get; set; } = new UserViewModel();
}
And then I've setup my ViewModel like this
public class UserViewModel : ObservableObject
{
public ObservableCollection<User> Users { get; set; } = new ObservableCollection<User>();
public UserViewModel()
{
Users.Add(new User{Name = "Riley"});
Users.Add(new User{Name = "Riley1"});
}
}
Simple, now I do have a ObservableObject that looks like this and deals with the INPC
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
And in my MainView.xaml
I've set the DataContext like so
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new BaseViewModel();
}
}
It's the exact same for the UserControl
And this is where I actually add the UserControl so it displays in the MainWindow
<ItemsControl ItemsSource="{Binding UserViewModel.Users}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<controls:UserCard/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Now the issue is that it doesn't bind the Data, I want to display the Name property from the Model but it's not displaying it and I am not sure why, if I try to bind it to a TextBlock property in the MainView directly it works fine.
I am unsure to why it's behaving like this and I would like to understand why.
Do I need to make use of DependencyProperties? Or is it just a case of me creating a new instance of the BaseViewModel? Where did I go wrong?
Your MainViewWindow contains an ItemsControl with the binding ItemsSource="{Binding UserViewModel.Users}", with each item being displayed with a <controls:UserCard/>. But your user control is then trying to bind to the list again with "{Binding UserViewModel.Users}". Why are you trying to display a list inside another list?
I suspect the problem here is that you think your custom UserControl's DataContext is still pointing to the BaseViewModel, like its parent. It isn't. The DataContext of each item in an ItemsControl points to it's own associated element in the list, i.e. an instance of type User.
UPDATED: Let's say you have a main view model with a list of child view models, like this:
public class MainViewModel : ViewModelBase
{
public MyChildViewModel[] MyItems { get; } =
{
new MyChildViewModel{MyCustomText = "Tom" },
new MyChildViewModel{MyCustomText = "Dick" },
new MyChildViewModel{MyCustomText = "Harry" }
};
}
public class MyChildViewModel
{
public string MyCustomText { get; set; }
}
And let's say you set your MainWindow's DataContext to an instance of MainViewModel and add a ListView:
<ListView ItemsSource="{Binding MyItems}" />
If you do this you'll see the following:
What's happening here is that the ListView is creating a container (of type ContentPresenter) for each of the three elements in the list, and setting each one's DataContext to point to its own instance of MyChildViewModel. By default ContentPresenter just calls 'ToString()' on its DataContext, so you're just seeing the name of the class it's pointing to. If you add a ToString() operator to your MyChildViewModel like this:
public override string ToString()
{
return $"MyChildViewModel: {this.MyCustomText}";
}
... then you'll see that displayed instead:
You can also override the ListViewItem's template entirely, and since it already points to its associated instance of MyChildViewModel you can just bind directly to its properties:
<ListView ItemsSource="{Binding MyItems}">
<ListView.ItemTemplate>
<DataTemplate>
<!-- One of these gets created for each element in the list -->
<Border BorderBrush="Black" BorderThickness="1" Background="CornflowerBlue" CornerRadius="5" Padding="5">
<TextBlock Text="{Binding MyCustomText}" Foreground="Yellow" />
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Which will change the display to this:
Make sense?
I am displaying the data in the gridview in a grouped style. I am already can create new items. Now I want to create a function that can delete the item that I create. Here is my viewmodel :
Viewmodel
public class VM : INotifyPropertyChanged
{
public VM()
{
DeleteItem = new DelegateCommand(DeleteCurrentItem);
}
public ObservableCollection<Contact> ContList = new ObservableCollection<Contact>();
private ObservableCollection<Category> _GroupedCollection;
public ObservableCollection<Category> GroupedCollection
{
get
{
if (_GroupedCollection == null)
_GroupedCollection = new ObservableCollection<Category>();
return _GroupedCollection;
}
set
{
_GroupedCollection = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("GroupedCollection"));
}
}
public void DeleteCurrentItem(object param)
{
var cont= param as Contact;
// there is another class that declare another ObservableCollection that holds all the models.
var category = GroupedCollection.FirstOrDefault(g => g.Key == cont.Account);
if (category != null)
{
if (category.CredCategory.Contains(cont))
{
category.CredCategory.Remove(cont);
}
}
}
public DelegateCommand DeleteItem { get; set; }
private string _Account;
public string Account
{
get { return _Account; }
set
{
_Account = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Account"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
In my XAML, I have a flyout, which work as desired. I can hold the data displayed and the flyout will appear/open. But when I click "Delete", the 'gridview' does not delete it.
View (XAML)
<Page.DataContext>
<data:VM/>
</Page.DataContext>
<Page.Resources>
<CollectionViewSource x:Key="cvs" IsSourceGrouped="True"
Source="{Binding GroupedCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemsPath="CredCategory"/>
</Page.Resources>
<Grid>
<FlyoutBase.AttachedFlyout>
<MenuFlyout x:Name="flyout">
<MenuFlyoutItem Text="Delete"
Command="{Binding DataContext.DeleteItem, ElementName=gridview}"
CommandParameter="{Binding}"/>
</MenuFlyout>
</FlyoutBase.AttachedFlyout>
<GridView x:Name="gridview"
ItemsSource="{Binding Source={StaticResource cvs}}"
<GridView.ItemTemplate>
<DataTemplate>
. . . .
<DataTemplate/>
<GridView.ItemTemplate>
<GridView/>
<Grid/>
I am showing the code-behind in case someone wants to see it.
View (Code-Behind)
public void cardstack_pass_Holding(object sender, HoldingRoutedEventArgs e)
{
//this is the event declared in the Datatemplate inside gridview
flyout.ShowAt(sender as FrameworkElement);
e.Handled = true;
}
As I stated at the above, my problem is when I click the "Delete" on flyout, it should be deleting the data from the ObservableCollection right? Because as far as I know, the DataContext of the flyout is the DataContext of the data displayed, or am I wrong? How to fix this?
I mean, the gridview's DataContext is the ObservableCollection, and the Stackpanels' DataContext inside gridview's DataTemplate will be the Model Contact right? Since flyout was open at the item created, so the DataContext of flyout will inherit from the item's DataContext, and if the flyout's CommandParameter = "{Binding}", it should pass the Contact inside the item to the viewmodel, isn't it?
I might be missing something here but shouldn't the AttachedFlyout code go in the DataTemplate
Note Binding of Command to element name root (Page name) as we're inside the GridView eg
<Page x:Name="root">
<Page.DataContext>
<data:VM/>
</Page.DataContext>
<Page.Resources>
<CollectionViewSource x:Key="cvs" IsSourceGrouped="True"
Source="{Binding GroupedCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemsPath="CredCategory"/>
</Page.Resources>
<Grid>
<GridView x:Name="gridview"
ItemsSource="{Binding Source={StaticResource cvs}}"
<GridView.ItemTemplate>
<DataTemplate>
<FlyoutBase.AttachedFlyout>
<MenuFlyout x:Name="flyout">
<MenuFlyoutItem Text="Delete"
Command="{Binding DataContext.DeleteItem, ElementName=root}"
CommandParameter="{Binding}"/>
</MenuFlyout>
</FlyoutBase.AttachedFlyout>
<DataTemplate/>
<GridView.ItemTemplate>
<GridView/>
<Grid/>
This article shows how to use Behaviours which are available in UWP.
I am new to MVVM and still trying to get a grasp on it so let me know if I'm setting this up wrong. What I have is a UserControl with a ListView in it. I populate this ListView with data from the ViewModel then add the control to my MainView. On my MainView I have a button that I want to use to add an item to the ListView. Here is what I have:
Model
public class Item
{
public string Name { get; set; }
public Item(string name)
{
Name = name;
}
}
ViewModel
public class ViewModel : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
private ObservableCollection<Item> _itemCollection;
public ViewModel()
{
ItemCollection = new ObservableCollection<Item>()
{
new Item("One"),
new Item("Two"),
new Item("Three"),
new Item("Four"),
new Item("Five"),
new Item("Six"),
new Item("Seven")
};
}
public ObservableCollection<Item> ItemCollection
{
get
{
return _itemCollection;
}
set
{
_itemCollection = value;
OnPropertyChanged("ItemCollection");
}
}
}
View (XAML)
<UserControl.Resources>
<DataTemplate x:Key="ItemTemplate">
<StackPanel Orientation="Vertical">
<Label Content="{Binding Name}" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<UserControl.DataContext>
<local:ViewModel />
</UserControl.DataContext>
<Grid>
<ListView ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding ItemCollection}">
</ListView>
</Grid>
MainWindow
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.mainContentControl.Content = new ListControl();
}
private void Button_Add(object sender, RoutedEventArgs e)
{
}
}
MainWindow (XAML)
<Grid>
<DockPanel>
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
<Button Width="100" Height="30" Content="Add" Click="Button_Add" />
</StackPanel>
<ContentControl x:Name="mainContentControl" />
</DockPanel>
</Grid>
Now, from what I understand, I should be able to just an item to ItemCollection and it will be updated in the view. How do I do this from the Button_Add event?
Again, if I'm doing this all wrong let me know and point me in the right direction. Thanks
You should not interact directly with the controls.
What you need to do is define a Command (a class that implements the ICommand-interface) and define this command on your ViewModel.
Then you bind the Button's command property to this property of the ViewModel. In the ViewModel you can then execute the command and add an item directly to your list (and thus the listview will get updated through the automatic databinding).
This link should provide more information:
http://msdn.microsoft.com/en-us/library/gg405484(v=pandp.40).aspx#sec11
Hello I have a application design problem and I home you can help me solve it....
This is my first application in silverlight and the first application using mvvm design pattern and I am not sure I am applying mvvm how I am supposed to..
The application is a dynamic application and at runtime I can add/remove usercontrols...
So I have a MainWindowView that has behind a MainWindowModel.
The MainWindowModel has a list of Workspaces witch are in fact WorkspaceModel classes...
I have multiple UserControls and everyone off them has his own view model witch inherits WorkspaceModel.
The Workspaces property is binded to a container in MainWindowView so adding to the Workspaces list a new UserControlModel will automatically add that control to the view.
Now where is my problem... I want to make this dynamically added usercontrols to interact. Lets say one user control is a tree and one is a grid... I want a method to say that Itemsource property of Grid UserControl Model (WorkspaceModel) to be binded to SelectedNode.Nodes Property from the Tree Usercontrol Model (WorkspaceModel).
The MainWindowModel has a property name BindingEntries witch has a list of BindingEntry...
BindingEntry stores the source property and the destination property of the binding like my workspacemodel_1.SelectedNode.Nodes -> workspacemodel_2.ItemSource...
Or as a variation the MainWindowView has a property ViewStateModel. This ViewStateModel class has dynamic created properties - "injected" with property type descriptors/reflections etc... So the user can define at run time the displayed usercontrols (by modifying the Workspaces list) and can define a view model (the ViewStameModel) and the binding is between workspacemodel properties and this ViewStateModel properties...
So I actually want to bind 2 view models one to another... How to do that?
Create an observer pattern?
Is the design until now totally wrong?
I hope it makes sense.....
I will try to add some sample code...the project is quite big I will try co put only the part I have mentioned in the problem desciption... I hope I will not miss any pice of code
First of all
public class MainWindowModel : ModelBase
{
private ObservableCollection<WorkspaceModel> _workspaces;
private ModelBase _userViewModel;
public MainWindowModel()
{
base.DisplayName = "MainWindowModel";
ShowTreeView(1);
ShowTreeView(2);
ShowGridView(3);
ShowGridView(4);
UserViewModel = new ViewModel(); //this is the ViewStateModel
}
void ShowTreeView(int id)
{
WorkspaceModel workspace = ControlFactory.CreateModel("TreeControlModel", id);
this.Workspaces.Add(workspace);
OnPropertyChanged("Workspaces");
SelectedWorkspace = workspace;
}
void ShowGridView(int id)
{
WorkspaceModel workspace = ControlFactory.CreateModel("GridControlModel", id);
this.Workspaces.Add(workspace);
OnPropertyChanged("Workspaces");
SelectedWorkspace = workspace;
}
public ObservableCollection<WorkspaceModel> Workspaces
{
get
{
if (_workspaces == null)
{
_workspaces = new ObservableCollection<WorkspaceModel>();
}
return _workspaces;
}
}
public ModelBase UserViewModel
{
get
{
return _userViewModel;
}
set
{
if (_userViewModel == value)
{
return;
}
_userViewModel = value;
OnPropertyChanged("UserViewModel");
}
}
}
snippets from MainappView
<DataTemplate x:Key="WorkspaceItemTemplate">
<Grid >
//workaround to use Type as in WPF
<Detail:DetailsViewSelector Content="{Binding}" TemplateType="{Binding}" >
<Detail:DetailsViewSelector.Resources>
<DataTemplate x:Key="TreeControlModel" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<TreeControl:TreeControlView />
</DataTemplate>
<DataTemplate x:Key="GridControlModel" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<GridControl:GridControlView />
</DataTemplate>
<DataTemplate x:Key="EmptyTemplate">
</DataTemplate>
</Detail:DetailsViewSelector.Resources>
</Detail:DetailsViewSelector>
</Grid>
</DataTemplate>
<DataTemplate x:Key="WorkspacesTemplate">
<ItemsControl IsTabStop="False" ItemsSource="{Binding}" ItemTemplate="{StaticResource WorkspaceItemTemplate}" Margin="6,2"/>
</DataTemplate>
</UserControl.Resources>
<toolkit:HeaderedContentControl Grid.Column="2" HorizontalAlignment="Stretch" Name="hccWorkspaces" VerticalAlignment="Top" Header="Workspaces" Content="{Binding Source={StaticResource vm}, Path=Workspaces}" ContentTemplate="{StaticResource WorkspacesTemplate}"/>
public class ControlFactory
{
public static WorkspaceModel CreateModel(string type, int id)
{
switch (type)
{
case "TreeControlModel": return new TreeControlModel() { Id=id}; break;
case "GridControlModel": return new GridControlModel() { Id = id }; break;
}
return null;
}
}
public class GridControlModel : WorkspaceModel
{
#region Fields
ObservableCollection<TreeItem> _items;
TreeItem _selectedItem;
#endregion // Fields
#region Constructor
public GridControlModel()
{
base.DisplayName = "GridControlModel";
}
#endregion // Constructor
#region Public Interface
public ObservableCollection<TreeItem> Items
{
get
{
return _items;
}
set
{
if (_items == value)
return;
_items = value;
OnPropertyChanged("Items");
}
}
public TreeItem SelectedItem
{
get
{
return _selectedItem;
}
set
{
if (_selectedItem.Equals(value))
{
return;
}
_selectedItem = value;
OnPropertyChanged("SelectedItem");
}
}
#endregion // Public Interface
#region Base Class Overrides
protected override void OnDispose()
{
this.OnDispose();
}
#endregion // Base Class Overrides
}
<Grid x:Name="LayoutRoot" Background="White">
<sdk:DataGrid Grid.Column="2" Grid.Row="1" HorizontalAlignment="Stretch" Name="dataGrid1" VerticalAlignment="Stretch" ItemsSource="{Binding Path=SelectedTreeNode.Children}" IsEnabled="{Binding}" AutoGenerateColumns="False">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="Id" Width="Auto" Binding="{Binding Id}" />
<sdk:DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="Name" Width="Auto" Binding="{Binding Name}"/>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
</Grid>
</UserControl>
For communicating between your view models I would suggest taking a look at the Messenger implementation in MVVM Light as a simple solution.
Alternatively, the Mediator Pattern as described here might be interesting: http://marlongrech.wordpress.com/2008/03/20/more-than-just-mvc-for-wpf/
I have MVVM master /details like this:
<Window.Resources>
<DataTemplate DataType="{x:Type model:EveryDay}">
<views:EveryDayView/>
</DataTemplate>
<DataTemplate DataType="{x:Type model:EveryMonth}">
<views:EveryMonthView/>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox Margin="12,24,0,35" Name="schedules"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Path=Elements}"
SelectedItem="{Binding Path=CurrentElement}"
DisplayMemberPath="Name" HorizontalAlignment="Left" Width="120"/>
<ContentControl Margin="168,86,32,35" Name="contentControl1"
Content="{Binding Path=CurrentElement.Schedule}" />
<ComboBox Height="23" Margin="188,24,51,0" Name="comboBox1"
VerticalAlignment="Top"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Path=Schedules}"
SelectedItem="{Binding Path=CurrentElement.Schedule}"
DisplayMemberPath="Name"
SelectedValuePath="ID"
SelectedValue="{Binding Path=CurrentElement.Schedule.ID}"/>
</Grid>
This Window has DataContext class:
public class MainViewModel : INotifyPropertyChanged {
public MainViewModel() {
elements.Add(new Element("first", new EveryDay("First EveryDay object")));
elements.Add(new Element("second", new EveryMonth("Every Month object")));
elements.Add(new Element("third", new EveryDay("Second EveryDay object")));
schedules.Add(new EveryDay());
schedules.Add(new EveryMonth());
}
private ObservableCollection<ScheduleBase> _schedules = new
ObservableCollection<ScheduleBase>();
public ObservableCollection<ScheduleBase> Schedules {
get {
return _schedules;
}
set {
schedules = value;
this.OnPropertyChanged("Schedules");
}
}
private Element _currentElement = null;
public Element CurrentElement {
get {
return this._currentElement;
}
set {
this._currentElement = value;
this.OnPropertyChanged("CurrentElement");
}
}
private ObservableCollection<Element> _elements = new
ObservableCollection<Element>();
public ObservableCollection<Element> Elements {
get {
return _elements;
}
set {
elements = value;
this.OnPropertyChanged("Elements");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
One of Views:
<UserControl x:Class="Views.EveryDayView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid >
<GroupBox Header="Every Day Data" Name="groupBox1" VerticalAlignment="Top">
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<TextBox Name="textBox2" Text="{Binding Path=AnyDayData}" />
</Grid>
</GroupBox>
</Grid>
My SelectedItem in ComboBox doesn't works correctly. Are there any visible errors in my code?
What I usually do is bind the items of an ItemsControl to an ICollectionView (usually ListCollectionView) instead of directly to a collection; I think that's what the ItemsControl does by default anyway (creates a default ICollectionView), but I might be wrong.
Anyway, this allows you to work with the CurrentItem property of the ICollectionView, which is automatically synchronized with the selected item in an ItemsControl (if the IsSynchronizedWithCurrentItem property of the control is true or null/default). Then, when you need the current item in the ViewModel, you can use that instead. You can also set the selected item by using the MoveCurrentTo... methods on the ICollectionView.
But as I re-read the question I realize you may have another problem altogether; you have a collection of 'default' items and need a way to match them to specific instances. It would however be a bad idea to override the equality operators of the objects to consider them always equal if they are of the same type, since that has the potential to make other code very confusing. I would consider extracting the type information into an enum, and put a read-only property on each object returning one of the enum values. Then you can bind the items to a collection of the enum values, and the selected item to the enum property of each object.
Let me know if you need an example, I may have made a mess of the explanation :)