WPF DataGrid TwoWay Binding - wpf

I have property UserSet which contains from ObservableCollection<GridRow>.
GridRow - my class, which contains 4 properties like this:
public int Id
{
get { return id; }
set
{
id = value;
RaisePropertyChanged("Id");
}
}
I populate UserSet, then Grid binds to it. When I change id field works setter Id. It sets right values.
But, after all changes, when I click other button my UserSet has not modified values. So I can't get updated Grid.
This is my XAML:
<DataGrid ItemsSource="{Binding UsersSet, Mode=TwoWay}" AutoGenerateColumns="True">
</DataGrid>
Please help.

You could try and set the UpdateSourceTrigger:
<DataGrid ItemsSource="{Binding UsersSet,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"
AutoGenerateColumns="True">
</DataGrid>
Without knowing the rest of your code it is pretty hard to guess.

Related

MVVM WPF - ComboBox two way binding inside ItemsControl

I am working on this problem for about a day now.
For some reason I am unable to TwoWay bind a value to a ComboBox if it is inside a ItemsControl. Outside works just fine.
I have an ObservableCollection of int? in my ViewModel:
private ObservableCollection<int?> _sorterExitsSettings = new ObservableCollection<int?>();
public ObservableCollection<int?> SorterExitsSettings
{
get { return _sorterExitsSettings; }
set
{
if (_sorterExitsSettings != value)
{
_sorterExitsSettings = value;
RaisePropertyChanged("SorterExitsSettings");
}
}
}
My XAML:
<ItemsControl ItemsSource="{Binding SorterExitsSettings}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl}, Path=DataContext.ScanRouter.Stores}"
SelectedValue="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="name" SelectedValuePath="id" IsEditable="True" />
</DataTemplate>
</ItemsControl.ItemTemplate>
So the ComboBox is populated with a list of stores. It works fine so far.
The ObservableCollection SorterExitsSettings even has some values set which are shown in the displayed ComboBoxes. So setting the SelectedValue also works.
However when I change a selection, SorterExitsSettings wont change. While when I implement the ComboBoxes(100) without an ItemsControl it suddenly works fine.
<ComboBox ItemsSource="{Binding ScanRouter.Stores}" DisplayMemberPath="name" SelectedValuePath="id" IsEditable="True" SelectedValue="{Binding SorterExitsSettings[0], Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
Even better when I implement the ComboBoxes using the ItemsControl and also the example ComboBox shown above. When I change the single ComboBox's value it will change the value of the ComboBox inside the ItemsControl, but not the other way around.
Did somebody encounter this problem before?
My guess was that the ItemsControl doesn't like the fact that I am binding my selected value to an item in a list. However when I bind directly to a ViewModel property(Store) it also doesn't work.
I also tried using SelctedItem instead of SelectedValue and populate the ObservableCollection with Store objects instead of int?.
The problem is that you're binding your ComboBox's SelectedValue directly to the collection elements which are type int ?. This won't work, binding targets have to be properties. Try wrapping your int ? values in a class and expose the value as a property of that class with a getter and setter, i.e. something like this:
private ObservableCollection<Wrapper> _sorterExitsSettings = new ObservableCollection<Wrapper>();
... etc...
And:
public class Wrapper
{
public int? Value {get; set;}
}
And finally:
<ComboBox ... SelectedValue="{Binding Path=Value, Mode=TwoWay...
Post back here if you still have problems.

WPF ListView does not get updated when changing item DisplayMemberPath MVVM

I have WPF ListView which bind to ObservableCollection.
Here is my ListView:
<ListView
BorderBrush="#6797c8"
BorderThickness="2"
ItemsSource="{Binding Path=MainCategoriesCollection, UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="Category"
SelectedValuePath="MainCatID"
SelectedItem="{Binding MainCategorySelectedItem}"
SelectedIndex="{Binding MainCategorySelectedIndex, Mode=TwoWay}"
FontSize="14"/>
and this is my ItemSource:
private ObservableCollection<DataModel.MainCategories> mainCategoriesCollection;
public ObservableCollection<DataModel.MainCategories> MainCategoriesCollection
{
get
{
if (mainCategoriesCollection == null)
{
mainCategoriesCollection = new ObservableCollection<DataModel.MainCategories>();
}
return mainCategoriesCollection;
}
set
{
mainCategoriesCollection = value;
RaisePropertyChanged("MainCategoriesCollection" );
}
}
I have wired problem. When I add items or delete item from MainCategoriesCollection my ListView get updated without any problem but when I take specific item and change the item property which represent "DisplayMemberPath" I can`t see the change in the ListView. I debugged the problem and saw that the change is exists in MainCategoriesCollection but my ListView refuse to show it.
Any ideas?
Ensure the DisplayMemberPath property is on a view model with all the INotifyPropertyChanged stuff, i.e. is the property observable?

Binding TwoWay to SelectedItem: "Wrong way" synchronization on initialization

I am trying to bind a property of my DataContext to the SelectedItem on a ComboBox like this:
<ComboBox x:Name="ElementSelector"
ItemsSource="{Binding Source={StaticResource Elements}}"
DisplayMemberPath="ElementName"
SelectedItem="{Binding ValueElement, Mode=TwoWay}">
where the Elements resource is a CollectionViewSource (don't know, whether this matters).
When everything is initialized, the property ValueElement of the DataContext is set to the first item in the CollectionViewSource. What I want, is to initialize it the other way around: I would like to set SelectedItem of the ComboBox to the value of the property or null if no matching item is contained.
How can this be done?
EDIT - Additional information:
The ComboBox is part of a DataTemplate:
<DataTemplate x:Key="ReferenceTemplate"
DataType="viewModels:ElementMetaReferenceViewModel">
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<ResourceDictionary>
<views:ElementsForReferenceViewSource x:Key="Elements"
Source="{Binding DataContext.CurrentProject.Elements, ElementName=Root}"
ReferenceToFilterFor="{Binding}"/>
</ResourceDictionary>
</StackPanel.Resources>
<TextBlock Text="{Binding PropertyName}"/>
<ComboBox x:Name="ElementSelector"
ItemsSource="{Binding Source={StaticResource Elements}}"
DisplayMemberPath="ElementName"
SelectedItem=""{Binding ValueElement, Mode=TwoWay}" />
</StackPanel>
</DataTemplate>
The ElementsForReferenceViewSource simply derives from CollectionViewSource and implements an additional DependencyProperty which is used for filtering.
The DataContext of the items in the CollectionViewSource look like this:
public class ElementMetaReferenceViewModel : ViewModelBase<ElementMetaReference, ElementMetaReferenceContext>
{
...
private ElementMetaViewModel _valueElement;
public ElementMetaViewModel ValueElement
{
get { return _valueElement; }
set
{
if (value == null) return;
_valueElement = value;
Model.TargetElement = value.Model;
}
}
...
}
For people encountering the same issue
The above code works as expected. The solution was getting the stuff behind the scenes right. Make sure, that the instance of the ViewModel which is the value of the property you want to bind to is definitely contained in the CollectionViewSource.
In my case the issue was deserializing an object tree incorrectly, so objects were instantiated twice. Then for each object a distinct ViewModel was initialized and then obviously the value of the property was not contained in the list.
Remark
To check whether this is an issue in your case, you can try the following:
Override the ToString() methods of the ViewModels displayed in the ComboBox like this:
public override string ToString()
{
return "VM"+ Model.GetHashCode().ToString();
}
Then you can easily compare the items in the source collection with the value on your property. Not the most professional way, but it did the job for me.

Bbinding combobox within dataform to view model property outside dataform's context

I have two properties in my view model:
//Relationship has property ReasonForEndingId
private Relationship editRelationship;
public Relationship EditRelationship
{
get
{
return editRelationship;
}
set
{
if (editRelationship != value)
{
editRelationship = value;
RaisePropertyChanged(EditRelationshipChangedEventArgs);
}
}
}
//ReasonForLeaving has properties Reason & Id
private IList<ReasonForLeaving> reasonsComboList { get; set; }
public IList<ReasonForLeaving> ReasonsComboList
{
get
{
return reasonsComboList;
}
private set
{
if (reasonsComboList != value)
{
reasonsComboList = value;
RaisePropertyChanged(ReasonsComboListChangedEventArgs);
}
}
}
In my xaml I have the following: (specifically note the binding on the dataform and combobox)
<toolkit:DataForm x:Name="EditForm" CurrentItem="{Binding EditRelationship, Mode=TwoWay}">
<toolkit:DataForm.EditTemplate>
<DataTemplate>
<StackPanel>
<toolkit:DataField>
<ComboBox x:Name="EndReasonCombo" ItemsSource="{Binding ReasonsComboList}" DisplayMemberPath="Reason" SelectedValuePath="Id" SelectedValue="{Binding ReasonForEndingId, Mode=TwoWay}"/>
</toolkit:DataField>
So, I'm trying to bind to a list that exists in my viewmodel (the datacontext for the page). However, the DataForm's datacontext is EditRelationship. ReasonsComboList does not exist within EditRelationship.
How can I bind the combobox so that it will display the list of items available in ReasonsComboList?
Thanks for your help!
Here's what I did (tested and works):
Within a DataForm this won't work (because its a DataTemplate) :
<ComboBox MinWidth="150" DisplayMemberPath="Name" Name="cbCompanies"
SelectedItem="{Binding TODOCompany,Mode=TwoWay}"
ItemsSource="{Binding ElementName=control, Path=ParentModel.Companies}" />
But you can do this instead:
<ComboBox MinWidth="150" DisplayMemberPath="Name" Name="cbCompanies"
SelectedItem="{Binding TODOCompany,Mode=TwoWay}"
Loaded="cbCompanies_Loaded"/>
Code behind:
private void cbCompanies_Loaded(object sender, RoutedEventArgs e)
{
// set combobox items source from wherever you want
(sender as ComboBox).ItemsSource = ParentModel.Companies;
}
if you set your datacontext using locator in this way
DataContext="{Binding FormName, Source={StaticResource Locator}}"
<ComboBox ItemsSource="{Binding FormName.ReasonsComboList, Source={StaticResource Locator}, Mode=OneWay}"
DisplayMemberPath="Reason" SelectedValuePath="Id"
SelectedValue="{Binding ReasonForEndingId, Mode=TwoWay}"/>
tested and working
I haven't tested this with your exact scenario, but you should be able to reference the DataContext of some parent element when binding the ItemsSource of the ComboBox. Basically using Silverlight's element-to-element binding to actually bind to some property on the parent container's DataContext instead of the current element's DataContext.
For example, if your main ViewModel was the DataContext of the LayoutRoot element you should be able to do something like this:
<ComboBox x:Name="EndReasonCombo" ItemsSource="{Binding DataContext.ReasonsComboList, ElementName=LayoutRoot}" DisplayMemberPath="Reason" SelectedValuePath="Id" SelectedValue="{Binding ReasonForEndingId, Mode=TwoWay}"/>
Creating a Silverlight DataContext Proxy to Simplify Data Binding in Nested Controls
Disclaimer: This may not actually work for the DataForm, but is suitable for the same problem when using a DataGrid. but I'm putting it here as an answer because it was an interesting read and helped me understand some things when I experienced the same problem.

Silverlight bind collection to Combobox in DataForm using MVVM

I have this problem, I've got Silverlight app written using MVVM. I need to create DataForm which is binded to property on ViewModel and I want to add ComboBox and fill it with values from other collection in the same ViewModel.
Code:
<dataFormToolkit:DataForm CurrentItem="{Binding NewUser, Mode=TwoWay}" AutoGenerateFields="False" Height="298">
<dataFormToolkit:DataForm.EditTemplate>
<DataTemplate>
<StackPanel>
<dataFormToolkit:DataField Label="Email">
<TextBox Text="{Binding Email, Mode=TwoWay}"/>
</dataFormToolkit:DataField>
<dataFormToolkit:DataField Label="Język">
<ComboBox ItemsSource="{Binding Path=Languages, Mode=TwoWay}"/>
</dataFormToolkit:DataField>
</StackPanel>
</DataTemplate>
</dataFormToolkit:DataForm.EditTemplate>
</dataFormToolkit:DataForm>
All this is handled by NewAccountVM which has these properties:
private User newUser;
public User NewUser {
get
{
return newUser;
}
set
{
if (value != newUser)
{
newUser = value;
RaisePropertyChanged("NewUser");
}
}
}
private ObservableCollection<Language> languages;
public ObservableCollection<Language> Languages
{
get { return languages; }
set
{
if (languages != value)
{
languages = value;
RaisePropertyChanged("Languages");
}
}
}
Now, all this works besides adding ItemsSource to ComboBox. I've found many examples showing how fill CB in CodeBehind, but like I said I want to do this in MVVM-Style :)
I understand that, ComboBox inherited DataContext from DataForm, and this ItemsSource="{Binding Path=Languages, Mode=TwoWay}" will not work, but I have no idea how to achieve my goal.
Can somebody help me?
1) Declare the viewmodel to the view in the resources section.
<UserControl.Resources>
<local:MyViewModel x:Key="myViewModel" />
</UserControl.Resources>
2) Bind the ComboBox to the collection property on the viewmodel.
<ComboBox ItemsSource="{Binding Path=Languages,
Source={StaticResource myViewModel},
Mode=TwoWay}"/>
you can set the Data Context in XAML to your static resource like so:
<UserControl.DataContext>
<Binding Source="{StaticResource myViewModel}" />
</UserControl.DataContext>
Scenario A:
1. Assume you wish to populate a combo with all the membership Roles, and allow the client to select the role and assign to the User :
i.e. ObjectA : Aspnet_Role
i.e. ObjectB : User
Let us say User.MembershipRoleId is to be bound to Aspnet_Role.RoleId
Dataform is bound to ObjectB
Combobox in dataform is populated with List
In XAML write the following:
<Combobox DisplayMemberPath="RoleName"
SelectedValue="{Binding MembershipRoleId,Mode=TwoWay}" SelectedValuePath="RoleId" />
here the mapping is, ObjectB.MembershipRoleId=ObjectA.RoleId
Scenario B:
1. If you do not want to explicitly define by the way in ScenarioA, then in that case, define a ForeignKey-PrimaryKey relationship between the tables in the database like
ForeignKey -> User.MembershipId
PrimaryKey -> Aspnet_Roles.RoleId
2. From the ADO.NET (.edmx) file, update the model from the database, you will observe that in the User entity there is an association made upon entity Aspnet_Roles
3. In XAML write the code as below to bind the combobox, to the desired field of the Dataform
<Combobox DisplayMemberPath="RoleName" SelectedItem="{Binding MembershipRoleId,Mode=TwoWay}" .... />

Resources