Shortest way to get display value from wpf combobox - wpf

To get the currently displayed value from a WPF combobox, I am getting GetSelectedItem (which gives me a dataRowView since my itemSource is a DataView) and then getting the appropriate column.
I was hoping there could be straightforward way to get the Display Value like how we have the SelectedValue property.
Is anyone aware of a better approach?

You use the ADO.Net class DataTable, right?
You can set a displayed value quite straightforward:
<ComboBox x:Name="myComboBox" ItemsSource="{Binding}" DisplayMemberPath="SomeColumn"
SelectedValuePath="SomeColumn"/>
In this example the combobox displays the value of the column SomeColumn. Put a correct column name instead of this dummy one.
And in code-behind:
myComboBox.DataContext = myDataSet.Customers; //any table
var selectedValue = myComboBox.SelectedValue; //The displayed value (SomeColumn)
var fullRow = myComboBox.SelectedITem; //dataRowView, I think

Related

WPF Datagrid bound to ViewModel.DataTable. SelectedItem not binding to ViewModel.SelectedObject

TYFYT. I need some help understanding what's going on here and how binding to a datagrid works. I am coming from a knowledge base of working with WinForms so maybe my approach is all wrong?...
I have a WPF window, with a Datagrid.
In the ViewModel I have DataTable that I have populated with my Booking objects. The cols across the top correspond to a TimeSlot, and the row headers correspond to an instructor.
void DisplayBookings()
{
foreach (Booking booking in bookings)
{ //Add each Booking object to the DataTable
DtBookings.Rows[booking.GridRow][booking.SlotTimeId + 1] = booking;
}
}
In the window xaml I have the datagrid bound to the DtBookings.
<DataGrid x:Name="grdInstructors"
ItemsSource="{Binding DtBookings}" DisplayMemberPath="Id"
SelectedItem="{Binding SelectedCell}"
When I run this, it's working fine. I see the bookings in the correct cells in the grid.
Trying to do work against the grid is what is raising questions.
Q1. What is the grid cell holding? I have put the Booking objects in the ViewModel.DataTable and in the grid cell I see "myNamespace.Models.Booking". This is fine but when I try to access it I get the error "'Unable to cast object of type 'System.String' to type 'MyObject' (Booking)
So is the datagrid only holding a String that is the name of the object? I could accept that answer since I'm thinking the View should only be a visual representation of the objects.
If that is so, then how should SelectedItem=ViewModel.MySelectedItem work? (In this case it doesn't). Initially I thought it should have a copy of the object so that when I click on the cell it will tell the ViewModel what object I have chosen. This normally works when I am bound to an ObservableCollection, but in this case it is bound to a DataTable so I'm not getting the same result.
And on a final note I have noticed that DisplayMemberPath="Id" doesn't work in this case. (It's not really an issue since I usually override `ToString())
It would be great to have a definitive answer on this before I add logic to work around the problem and defeat the point of MVVM and Binding.
TYVM.

Selecteditem event in MVVM silverlight

i have a datagrid bound to a property. In this grid i have columns which consists of cells which are like hyperlink i mean when user clicks on the cell value based on these values another gird will get populated. i want to know how to get the cell value and pass it to some method so that other grid will get populated.
The best way to do this is in your viewmodel.
You should bind the SelectedItem of your datagrid to a new property in your ViewModel. In the set method of this new Property, call a new method to populate a new ObservableCollection/List/whatever...
Finally, bind your "other grid" ItemsSource to this new observable collection from your ViewModel.
Edit:
If you need to load one thing or another depending on the column you are going to use the code behind, take a look at this:
Silverlight DataGrid how to get cell value from a selected item?

DataGrid SelectedItem Binding

Below is the code behind in my view model:
private DataRow selectedErrorRow;
public DataRow SelectedErrorRow
{
get { return selectedErrorRow; }
set { selectedErrorRow = value; base.RaisePropertyChanged("SelectedErrorRow"); }
}
Then this in my view:
<DataGrid SelectedItem="{Binding SelectedErrorRow,Mode=TwoWay}"
The binding somewhat works... It "gets" the value when the datagrid is drawn but it never sets it when a new value is selected/highlighted.... Any ideas?
Note the item source for the datagrid is a DataTable.
EDIT:
The Datagrid is in a PopUp, when the datagrid gets drawn it will get the binded value (null). However once I selected/highlight a row it will NOT 'set' anything. It will however 'set' the binded value null when its redrawn (the popup is open, i selected a row, close it,and reopen it). The thing is It never sets the value to anything but null, and it only sets it during the secound time its drawn.
I needed to change what I was binding to. It needs to bind to a DataRowView and not a DataRow.
I had this issue previously and figured it out myself.
It is not intuitive to know what is the issue since you cannot see the real value in debug but when you data bind a DataTable on a datagrid at first you think it has a DataTable type as source right ? Well you are wrong if you think that.
Actually the datagrid or the binding (i still don't know where it happen as i only see DataTable on my side) does a cast/convert of DataTable object like DataTable.AsDataView() to convert it to a DataView by itself so the selected item make sense to me to be DataRowView.
I know it's old question but this might shed light to those who get here and also look to set value as data source especially converters
Try this:
DataGrid SelectedItem="{Binding Path=SelectedErrorRow,Mode=TwoWay}
This should solve your problem.

Looping through (and removing) items of a bound ComboBox

I am new to WPF - and painfully aware of it. I have unsuccessfully searched for answers to this particular problem and am now seeking advice from my more knowledgeable peers!
The scenario
The application on which I am working allows users to either enter new records into a database, or amend existing ones.
I have a form containing a bound ComboBox. It is populated from the database, which is accessed by a WPF service that exposes a DTO.
From the UI perspective, the form has two modes:
1. enter new record
2. amend existing record
The ComboBox in question appears in both cases, but the requirement is to have fewer options visible when the form is in 'amend' mode.
What I am trying to do is loop through the ComboBox items when the form is in 'amend' mode and remove/hide the options that should not appear.
The XAML
<ComboBox x:Name="RecordType" Grid.Column="1" Grid.Row="1" Width="150" HorizontalAlignment="Left" SelectedValue="{Binding Path=RecordTypeID,TargetNullValue=0}"/>
The code behind - and my (feeble!) attempts so far
foreach (ComboBoxItem item in this.RecordType.Items)
{
if (IsApplicable(item.Content.ToString()) == false)
{
item.Visibility = Visibility.Hidden;
}
}
(NOTE: IsApplicable() is a simple method that compares the string it receives to a list of the options that are allowed to appear when the form is in 'amend' mode.)
The problem
As I'm sure many of you will already know ... cannot cast object of type DTO to type System.Windows.Controls.ComboBoxItem
The question(s)
Can I get at the string values in this, or a similar way? If so, how, please?
Correct way to do this would be to apply Filter on Collection View
See Automatically Filtering a ComboBox in WPF
ICollectionView view = CollectionViewSource.GetDefaultView(comboBox.ItemsSource);
view.Filter = IsApplicable
view.Refresh(); // <-- call this whenever you change the view model
It would likely be easier for you if you bound your combobox to an ObservableCollection and then removed the items from the collection when needed.
Here is an example: http://www.tanguay.info/web/index.php?pg=codeExamples&id=304

Silverlight: How can I set a converter on a ComboBox ItemsSource in the code-behind?

I have a combobox that is populated at runtime with values from a loadoperation (I'm using RIA services)
cboSite.ItemsSource = lo.Entities;
However, I want to be able to add a null item to the top of the list shown in the combobox, so following the example given here:
http://clr-namespace.com/post/SilverlightWPF-ComboBox-with-Empty-Item-allows-user-to-go-back-to-no-selection.aspx
I am trying to use a converter to insert the item at the top of the list. However, the problem I have is that I can't seem to work out how to specify the converter in the code behind!
Any ideas how to achieve this?
If you are willing to assign ItemsSource from the code-behind you can convert your Entities in the same very place. Something like this:
var converter = new AddEmptyItemConverter();
var converted = (IEnumerable<Entity>)converter.Convert(lo.Entities,
typeof(IEnumerable<Entity>),
null,
null);
cboSite.ItemsSource = converted;
That Entity should be the type of Entities collection element.

Resources