ComboBox Binding Collection and Selected Property - wpf

Why doesn't #2 work? (It seems like most examples say to do this).
#1(works)<ComboBox ItemsSource="{Binding Marker.ReadOnlyContentRegions}"
SelectedItem="{Binding Marker.SelectedRegion}"
SelectedValue="{Binding
Marker.SelectedRegion.UniqueId, Mode=TwoWay}"
SelectedValuePath="UniqueId"
DisplayMemberPath="Label" />
#2(doesn't work)<ComboBox ItemsSource="{Binding Marker.ReadOnlyContentRegions}"
SelectedValue="{Binding Marker.SelectedRegion.UniqueId,Mode=TwoWay}"
SelectedValuePath="UniqueId"
DisplayMemberPath="Label" />
This is the class that contains the objects that should be databound.
class...
public CancellableObservableCollection<InvisibleContentMarkerBase>
ReadOnlyContentRegions
{
get { return
CancellableObservableCollection<InvisibleContentMarkerBase>)
GetValue(ReadOnlyContentRegionsProperty); }
set { SetValue(ReadOnlyContentRegionsProperty, value); }
}
public static readonly DependencyProperty ReadOnlyContentRegionsProperty =
DependencyProperty.Register("ReadOnlyContentRegions",
typeof(CancellableObservableCollection<InvisibleContentMarkerBase>),
typeof(TargetedContentMarker), new UIPropertyMetadata(null);
public InvisibleContentMarkerBase SelectedRegion
{
get { return (InvisibleContentMarkerBase)GetValue(SelectedRegionProperty); }
set { SetValue(SelectedRegionProperty, value); }
}
public static readonly DependencyProperty SelectedRegionProperty =
DependencyProperty.Register("SelectedRegion",
typeof(InvisibleContentMarkerBase), typeof(TargetedContentMarker), new
UIPropertyMetadata(null));
...// end of class

First of all, don't set both the SelectedItem and the SelectedValue
They both set the exact same property, so when you set both only one value will actually get used
When you set SelectedValuePath and SelectedValue, you are setting the selected item by value. The SelectedValuePath tells WPF what property on objects in the collection is the Id field, and SelectedValue tells WPF to set the selected item to the value that is equal to SelectedValue.
SelectedItem simply tells WPF to select the item in the collection that exactly matches the SelectedItem object. Note that this comparison is by reference, so if the SelectedItem is a class that doesn't point to the exact same reference in memory as one of the objects in the ItemsSource, it won't evaluate the two objects as the same and won't set the item as Selected
So in short, either get rid of the SelectedItem binding and just use SelectedValue/SelectedValuePath, or remove SelectedValue/SelectedValuePath and ensure that the object bound in SelectedItem refers to the exact same object in memory as the copy in the ItemsSource.
If you really can't reference that object, and insist on using SelectedItem instead of SelectedValue, you could also overwrite the .Equals() on your class so it returns true if the data is equal, regardless of if the memory reference is the same. I prefer to avoid this since this changes the functionality of any instances of this class, but wanted to let you know that option is available.

Related

Avoid Two way binding between objects in C#

When i assign a value of a class object to other class object and when i change a property of 1st object it reflects in other object.
Example:
class A has property of type int Aid
SelectedA is a property of a Viewmodel Class which is binded to A WPF View.
SelectedA.Aid is in TwoWay binding with a combo box.
i have created another object objectA and assigned objectA=SelectedA.
Problem when i change combobox value value of objectA.Aid is also changed.
Thanks in advanced i need to avoid binding of objectA with SelectedA.
Vehicle dbvalue
private Vehicle _selectedA;
public Vehicle SelectedA
{
get { return _selectedA; }
set
{
_selectedA = value;
RaisePropertyChanged("SelectedA");
}
}
public partial class A
{
public int AID { get; set; }
public string AName { get; set; }
}
<ComboBox
DisplayMemberPath="AName"
ItemsSource="{Binding items}"
SelectedValue="{Binding SelectedA.AID}"
SelectedValuePath="AName "/>
In viewmodel Class
i have used
dbvalue = SelectedA;
When i change combobox value dbvalue.AID is also changed.
You can set the behaviour of your SelectedValue binding to only update when the source changes.
SelectedValue="{Binding SelectedA.AID, Mode=OneWay}"
These are the other possible values for the Binding Mode lifted from the MSDN site:
TwoWay updates the target property or the property whenever either the target property or the source property changes.
OneWay updates the target property only when the source property changes.
OneTime updates the target property only when the application starts or when the DataContext undergoes a change.
OneWayToSource updates the source property when the target property changes.
Default causes the default Mode value of target property to be used.
Original MSDN article
To prevent of this problem, you can set it each property of object as follows:
objectA.AId = SelectedA.AId
objectA.AName = SelectedA.AName
Good Luck

Binding to an initially NULL property in the ViewModel doesn't rebind

I have a UserControl that contains a Telerik RadDataForm. The form's ItemsSource is bound to a property on the UserControl's ViewModel:
<telerik:RadDataForm
ItemsSource="{Binding Path=viewModel.items, RelativeSource={RelativeSource AncesterType=local:MyUserControl}}"
/>
Where viewModel is:
public partial class MyUserControl: UserControl
{
public MyUserControlVM viewModel
{ get { return this.DataContext as MyUserControlVM; } }
}
Within the viewmodel, items is a fairly ordinary collection:
public class MyUserControlVM : MyViewModelBase
{
private ObservableCollection<AnItem> items_;
public ObservableCollection<AnItem> items
{
get { return this.items_; }
set
{
this.items_ = value;
notifyPropertyChanged("items");
}
}
...
}
And where, of course, MyViewModelBase implements INotifyPropertyChanged.
The user control has an items dependency property, and when it is set, it sets the matching property on the view model:
public partial class MyUserControl : UserControl
{
public ObservableCollection<AnItem> items
{
get { return GetValue itemsProperty as ObservableCollection<AnItem>; }
set { SetValue(itemsProperty, value); }
}
public static readonly DependencyProperty itemsProperty =
DependencyProperty.Register("items",
typeof(ObservableCollection<AnItem>),
typeof(MyUserControl), new PropertyMetadata(
new PropertyChangedCallback(itemsPropertyChanged)));
private static void itemsPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
MyUserControl myUserControl = d as MyUserControl;
ObservableCollection<AnItem> items =
e.NewValue as ObservableCollection<AnItem>;
if (myUserControl != null && myUserControl.viewModel != null)
myUserControl.viewModel.items = items;
}
}
All of which seems pretty straightforward, if a bit tedious.
The problem is that the items dependency property on MyUserControl is bound to a property of the current item of another collection, and that the current item is initially null, and so when MyUserControl is initially loaded, its items property is null. And hence, so is the items property on MyUserControlVM that the RadDataForm is binding to.
Later, when an item in that outer collection is made current, the items dependency property on MyUserControl is set, and that sets the items property on MyUserControlVM. And MyUserControlVM calls notifyPropertyChanged so that listeners will be informed of the change. But this last is not working.
Afterwards, if I examine RadDataForm, its ItemsSource property is still null.
It's like the RadDataForm isn't listening for the propertychanged event, because what it was bound to was initially null. In similar circumstances where the bound property is not null at the start, this pattern works fine as the current item changes from one item to another, but it doesn't seem to work from having no current item to having one.
So, any ideas as to how to make this work? I can't, given the circumstances, make it so that items always has a value when the form loads - it is always going to be null, at the start. How do I get the RadDataForm to notice when the property becomes non-null?
When I want to reference something at the root of my UserControl (a custom property, for instance, or as in your case, the DataContext), I usually give my UserControl a Name. Then I use this name together with the ElementName property on the Binding to set it up.
<UserControl
...
Name="TheControl">
<Grid>
<TextBlock Text={Binding Path=DataContext.items, ElementName=TheControl}" />
</Grid>
</UserControl>
Due to the viewModel property, you can use that and DataContext interchangeably.
However, in your case it might actually be simpler. First, there's a typo in your code. It should be AncestorType (with an 'o'). Second, you might want to try setting up the binding using only {Binding Path=items} since I believe that your control already inherits the correct DataContext. (Not sure about that last one, though.)
If the problem persists, and you suspect that it does in fact has something to do with the items property returning null initially, you could always initialize the items_ with an empty collection to avoid the null.
private ObservableCollection<AnItem> items_ = new ObservableCollection<AnItem>();

How to get the value from DataGrid's SelectedItem?

In my project i have one Datagrid and i bind the following fields that are listed below.
CustomerID, Name, Email.
I have the Entity named WS_Customer. i have put one button control for all row in datagrid.If i click the button means the i need to get the CustomerID value.
How to get it.
If i put like this means,
WS_Customer getid=(WS_Customer)DG.SelectedItem;
getidshows null..
How i got the value?
Assuming you are using MVVM... and you DataGrid is bound to a collection of the WS_Customer objects you can put a property in your view model that you can bind to the SelectedItem property of the DataGrid. Keep in mind the row must be selected for the SelectedItem property to have a value.
In xaml:
<DataGrid SelectedItem="{Binding SelectedWS_Customer}" />
In viewModel:
public WS_Customer SelectedWS_Customer
{
get
{
return _selectedWS_Customer; //private variable
}
set
{
_selectedWS_Customer = value;
}
}

Difference between SelectedItem, SelectedValue and SelectedValuePath

What is the difference betweeen the following:
SelectedItem
SelectedValue
SelectedValuePath
All these dependency properties are defined in Selector class. I often confuse SelectedItem with SelectedValue , and SelectedValue with SelectedValuePath.
I would like to know the difference between them, and also when do we use them, especially SelectedValue and SelectedValuePath. Please explain their use with some simple examples.
Their names can be a bit confusing :). Here's a summary:
The SelectedItem property returns the entire object that your list is bound to. So say you've bound a list to a collection of Category objects (with each Category object having Name and ID properties). eg. ObservableCollection<Category>. The SelectedItem property will return you the currently selected Category object. For binding purposes however, this is not always what you want, as this only enables you to bind an entire Category object to the property that the list is bound to, not the value of a single property on that Category object (such as its ID property).
Therefore we have the SelectedValuePath property and the SelectedValue property as an alternative means of binding (you use them in conjunction with one another). Let's say you have a Product object, that your view is bound to (with properties for things like ProductName, Weight, etc). Let's also say you have a CategoryID property on that Product object, and you want the user to be able to select a category for the product from a list of categories. You need the ID property of the Category object to be assigned to the CategoryID property on the Product object. This is where the SelectedValuePath and the SelectedValue properties come in. You specify that the ID property on the Category object should be assigned to the property on the Product object that the list is bound to using SelectedValuePath='ID', and then bind the SelectedValue property to the property on the DataContext (ie. the Product).
The example below demonstrates this. We have a ComboBox bound to a list of Categories (via ItemsSource). We're binding the CategoryID property on the Product as the selected value (using the SelectedValue property). We're relating this to the Category's ID property via the SelectedValuePath property. And we're saying only display the Name property in the ComboBox, with the DisplayMemberPath property).
<ComboBox ItemsSource="{Binding Categories}"
SelectedValue="{Binding CategoryID, Mode=TwoWay}"
SelectedValuePath="ID"
DisplayMemberPath="Name" />
public class Category
{
public int ID { get; set; }
public string Name { get; set; }
}
public class Product
{
public int CategoryID { get; set; }
}
It's a little confusing initially, but hopefully this makes it a bit clearer... :)
Chris
To answer a little more conceptually:
SelectedValuePath defines which property (by its name) of the objects bound to the ListBox's ItemsSource will be used as the item's SelectedValue.
For example, if your ListBox is bound to a collection of Person objects, each of which has Name, Age, and Gender properties, SelectedValuePath=Name will cause the value of the selected Person's Name property to be returned in SelectedValue.
Note that if you override the ListBox's ControlTemplate (or apply a Style) that specifies what property should display, SelectedValuePath cannot be used.
SelectedItem, meanwhile, returns the entire Person object currently selected.
(Here's a further example from MSDN, using TreeView)
Update: As #Joe pointed out, the DisplayMemberPath property is unrelated to the Selected* properties. Its proper description follows:
Note that these values are distinct from DisplayMemberPath (which is defined on ItemsControl, not Selector), but that property has similar behavior to SelectedValuePath: in the absence of a style/template, it identifies which property of the object bound to item should be used as its string representation.
SelectedItem and SelectedValue are an object.
and SelectedValuePath is a string.
for example using the ListBox:
Below listbox1.SelectedValue becomes a string value.
string value = listbox1.SelectedValue;
if you say give me listbox1.SelectedItem it will give you the entire object.
ListItem item = listbox1.SelectedItem;
string value = item.value;
inspired by this question I have written a blog along with the code snippet here. Below are some of the excerpts from the blog
SelectedItem – Selected Item helps to bind the actual value from the DataSource which will be displayed. This is of type object and we can bind any type derived from object type with this property. Since we will be using the MVVM binding for our combo boxes in that case this is the property which we can use to notify VM that item has been selected.
SelectedValue and SelectedValuePath – These are the two most confusing and misinterpreted properties for combobox. But these properties come to rescue when we want to bind our combobox with the value from already created object. Please check my last scenario in the following list to get a brief idea about the properties.
Every control that uses Collections to store data have SelectedValue, SelectedItem property. Examples of these controls are ListBox, Dropdown, RadioButtonList, CheckBoxList.
To be more specific if you literally want to retrieve Text of Selected Item then you can write:
ListBox1.SelectedItem.Text;
Your ListBox1 can also return Text using SelectedValue property if value has set to that before. But above is more effective way to get text.
Now, the value is something that is not visible to user but it is used mostly to store in database. We don't insert Text of ListBox1, however we can insert it also, but we used to insert value of selected item. To get value we can use
ListBox1.SelectedValue
Source

WPF derived ComboBox SelectedValuePath issue

In our application we have a very large set of data that acts as our data dictionary for ComboBox lists, etc. This data is staticly cached and keyed off of 2 variables, so I thought it wise to write a control that derived from ComboBox and exposed the 2 keys as DPs. When those 2 keys have proper values I set the ItemsSource of the ComboBox automatically from the data dictionary list it corresponds to. I also automatically set the SelectedValuePath and DisplayMemberPath in the constructor to Code and Description, respectively.
Here's how an example of how an item in the ItemsSource from the data dictionary list always looks:
public class DataDictionaryItem
{
public string Code { get; set; }
public string Description { get; set; }
public string Code3 { get { return this.Code.Substring(0, 3); } }
}
The value of Code is always 4 characters long, but sometimes I only need to bind 3 characters of it. Hence, the Code3 property.
Here's how the code looks inside my custom combobox to set the ItemsSource:
private static void SetItemsSource(CustomComboBox combo)
{
if (string.IsNullOrEmpty(combo.Key1) || string.IsNullOrEmpty(combo.Key2))
{
combo.ItemsSource = null;
return;
}
List<DataDictionaryItem> list = GetDataDictionaryList(combo.Key1, combo.Key2);
combo.ItemsSource = list;
}
Now, my problem is, when I change the SelectedValuePath in the XAML to Code3, it doesn't work. What I bind to SelectedValue still gets the full 4 character Code from DataDictionaryItem. I even tried rerunning SetItemsSource when the SelectedValuePath was changed and no dice.
Can anyone see what I need to do to get my custom combobox to wake up and use the SelectedValuePath provided if it's overridden in the XAML? Tweaking the value in the property setter in my SelectedValue bound business object is not an option.
Here's how the XAML looks for my combobox in a form:
<c:CustomComboBox Key1="0" Key2="8099" SelectedValuePath="Code3" SelectedValue="{Binding Thing}"/>
EDIT: I just ran snoop on my code and it says my SelectedValuePath is Code... it doesn't appear to ever be set to Code3... Zuh?
Ok, I figured it out.
Apparently setting the default values of a DependencyProperty in the default non-static constructor of a WPF control is a no-no. So, at first I tried this:
static ValueCodeListComboBox()
{
SelectedValuePathProperty.OverrideMetadata(typeof(ValueCodeListComboBox), new PropertyMetadata("Code"));
DisplayMemberPathProperty.OverrideMetadata(typeof(ValueCodeListComboBox), new PropertyMetadata("Description"));
}
But this kept throwing an error saying:
Metadata override and base metadata must be of the same type or derived type.
Finally figured out that meant I needed to use FrameworkPropertyMetadata instead of PropertyMetadata:
static ValueCodeListComboBox()
{
SelectedValuePathProperty.OverrideMetadata(typeof(ValueCodeListComboBox), new FrameworkPropertyMetadata("Code"));
DisplayMemberPathProperty.OverrideMetadata(typeof(ValueCodeListComboBox), new FrameworkPropertyMetadata("Description"));
}
Now changing SelectedValuePath in the XAML works great.

Resources