I'm using a combobox to show categories a user can choose.
All those items have the id as the SelectedValuePath so I can easly get those when the user makes a selection.
<ComboBox Grid.Column ="1" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Name="cboCategorieen" ItemsSource="{Binding}" DisplayMemberPath="naam" SelectedValuePath="id" />
But how can I change the selection of the combobox when I have the id of the chosen selection (SelectedValuePath)?
This code doesn't do anything and just keeps selecting the first one.
cboCategorieen.SelectedValuePath = Convert.ToString(artikelWijzigen.categorie);
To conclude:
How can I change the selection of the combobox to the one matching the id?
I would suggest you to follow MVVM, Still the answer for your question would be Say if you have a ItemsSource like this,
ObservableCollection<YourComboBoxClass> wsWebshopMRentals;
You can set the selectedItem of combobox like this,
cboCategorieen.SelectedValue = wsWebshopMRentals.FirstOrDefault(x => x.Id == YourID).naam;
Related
I have a ComboBox in WPF. The ComboBox is inside of a grid, and the grid's DataContext is bound to the SelectedItem of a ListView. The ItemsSource of the ComboBox is set to a StaticResource, located in the window resources. The ItemsSource does not change. I have tried to use both SelectedValue and SelectedItem but both of them cause the same issue for me. The issue is that when the SelectedItem of the ListView is changed, the ComboBox is actually setting the property value from the PREVIOUSLY selected item, to the property value of the NEWLY selected item. Clearly I am doing something wrong, because I have used comboboxes many times in the past without this issue. I have scoured the web and can't find an answer. The closest, most similar question I found was: Strange behaviour (or bug?) with ComboBox in WPF when changing DataContext and having bound ItemsSource and SelectedItem
But it doesn't seem to have a solution. The solutions listed in comments did not work for me.
I created SelectionChanged events for both the ListView and the ComboBox and set breakpoints at each of them and the property that is being set. The property is actually being set BEFORE either one of those are triggered. So even if I wanted to create some hack workaround, I couldn't.
For the record, the ComboBox functionality works perfectly fine. When an object is selected in the ListView, I can see the Template name property, as I should, and the list of items is correct. If I manually change the selected item, the property is changed to a new item, just like it should. The problem is that when I change the selected item in the ListView, the "Template" property of the newly selected object is being set to the "Template" property of the previously selected object. So the combobox is changing before anything else.
The xaml for the ListView and ComboBox are below.
<ListView x:Name="my_ListBox" FlowDirection="RightToLeft"
Margin="5" Grid.RowSpan="2" SelectedIndex="0"
ItemsSource="{Binding Source={StaticResource myList}}"
DisplayMemberPath="Name"
SelectionChanged="my_ListBox_SelectionChanged"/>
<Grid DataContext="{Binding ElementName=my_ListBox, Path=SelectedItem}">
<ComboBox Name="comboBox_myTemplate"
ItemsSource="{Binding Source={StaticResource myTemplatesList}}"
SelectedValue="{Binding Template}"
SelectionChanged="comboBox_myTemplate_SelectionChanged"
DisplayMemberPath="Name" FontSize="20" Margin="5"/>
</Grid>
If I set "IsSynchronizedWithCurrentItem="True"" in the ComboBox the problem is resolved. If someone wants to explain what exactly that is doing and how it works I'd love to hear it. Thanks.
I have a WPF applications with a User Control that contains a couple combo boxes. One of the combo boxes is populated and displays the first value because it is bound to an IEnumerable property of enum values. The other is bound to an IEnumerable property of string values. This displays all the choices in the drop down, but does not display a value when it is first loaded. After selecting an option, the user is able to click the clear button, which will remove their selected option, and display the first value in the list until another value is chosen. Is there a way for me to get it to load with the first value already populated as the default value?
User Control:
<ComboBox x:Name="insuranceTypesComboBox" ItemsSource="{Binding Path=InsuranceTypes}" SelectedItem="{Binding Path=FilteredType}" Width="100" />
<ComboBox x:Name="insurancesComboBox" ItemsSource="{Binding Path=Insurances}" SelectedItem="{Binding Path=FilteredPlan}" Width="100"/>
Properties:
public IEnumerable<string> Insurances
{
get
{
var insurances = (from i in this.repository.GetInsurance()
select i.CompanyName).ToList();
return insurances.Distinct();
}
}
public IEnumerable<InsuranceType> InsuranceTypes
{
get
{
return Enum.GetValues(typeof(InsuranceType)) as IEnumerable<InsuranceType>;
}
}
You can select the first item in the combobox by adding SelectedIndex=0 to the xaml. Or try adding UpdateSourceTrigger=PropertyChanged to the selected item binding:
<ComboBox x:Name="insuranceTypesComboBox"
ItemsSource="{Binding Path=InsuranceTypes}"
SelectedItem="{Binding Path=FilteredType, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
Width="100"
SelectedIndex="0" />
To set the default item that is selected, just use (for example):
myComboBox.SelectedIndex = 5; // set the 6th item in list as selected
or you can use combobox.SelectedValue.
Make sure that you don't accidentally trigger the index changed event.
please refer selectedindex_selectedvalue
I have a collection of Contact objects that I've bound as follows in a WPF form:
<ComboBox Name="Name"
Text="{Binding Path=Contact.FullName}"
ItemsSource="{Binding ContactsCollection}"
SelectedItem="{Binding Path=Contact, Mode=TwoWay}"
IsEditable="true"
IsTextSearchEnabled="True"
TextBoxBase.TextChanged="Name_TextChanged"/>
<TextBox Name="Position" Text="{Binding Path=Contact.Position}"/>
<TextBox Name="Phone" Text="{Binding Path=Contact.PhoneNumber}"/>
I'd like the contact to be selected when the user starts typing in the combo 'IsTextSearchEnabled=true'.
The problem is that I'd like the items in the collection to remain read-only. Once a contact has been selected, any text deletes or additions modify the contact name in the collection.
How can I bind a collection to a combobox, enable search and prevent edits to the collection?
I could be missing something here, but if you don't want an editable ComboBox, try not setting the ComboBox.IsEditable property to True. Using this simple code, I can display items in a ComboBox and make selections by typing (when the ComboBox is focused) without editing anything:
<ComboBox ItemsSource="{Binding Items}" IsTextSearchEnabled="True" Height="25" />
Thanks for your input. It sorted me out. Removing the SelectedItem property and setting Position and PhoneNumber in the PropertyChanged event was what I needed.
I want to bind my collection of countries to a Combobox.
My XAML page looks as follows:
<pmControls:pmComboBox
Margin="3" Grid.Row="5" Grid.Column="1"
ItemsSource="{Binding Path=Countries}"
SelectedValue="{Binding Title,Mode=TwoWay}" >
</pmControls:pmComboBox>
I want to display Title as DataTextField.
Currently it shows namespace of country class in my combobox list .
I have also tried to add DisplayMemberPath but it also not works.
How can I setup the display field of Combobox to use a Binding?
I think you need to do
DisplayMemberPath="Title"
SelectedValuePath="Title"
SelectedValue="{Binding Path=Country,Mode=TwoWay}"
I have a ComboBox in WPF which is databound, and has data template which controls how each of the items is displayed. I have made it so that each item is displayed with two bits of text (for the Name and Path properties) and one image (for the Icon property).
At the moment when I select an item from the ComboBox the textbox bit of the ComboBox just changes to say "TestWPF.Result" which is the name of the class which I have populated the ComboBox with.
I'm interested in one (or both) of two things:
How do I change it so that it displays the value of one of the fields there (eg. so it shows the value of the Name field rather than the name of the class)?
Is it possible get it to use the same DataTemplate there as in the list of items, so that once I have selected an item it displays in the closed ComboBox the same way as it looks in the list of items. Basically I've got a DataTemplate called ShowResults and a ComboBox which uses that template. I've also added in a separate ContentControl which I've got to show the details of the selected item in the ComboBox, but I want to get that to replace the textbox in the ComboBox.
Update:
Thanks for the first answer. I've tried using a separate ContentControl, as you've described, and it works fine. The question now is how to replace the textbox part of the ComboBox with this ContentControl. Any hints on that would be most welcome.
Also, is it possible to replace the textbox bit of the ComboBox control with a mixture of the ContentControl and a textbox, so that I can still type in the textbox to help select items from the ComboBox, but then when I close the dropdown the rest ContentControl bit will be populated with the rest of the text and the icon. Hope that makes sense - ask questions if it doesn't!
Code:
I've been asked to post my code - so here it is. I've tried to remove things that I know are definitely not relevant, but I'm not sure exactly what is relevant so when in doubt I've left things in.
<Window x:Class="TestWPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:custom="clr-namespace:TestWPF"
Title="Window1" Height="300" Width="843" Loaded="Window_Loaded">
<Window.Resources>
<DataTemplate x:Key="ShowResult" DataType="TestWPF.Result">
<StackPanel Margin="5" Orientation="Horizontal">
<Image Width="32" Height="32" Source="{Binding Path=Image}"/>
<StackPanel Margin="5">
<TextBlock FontWeight="Bold" Text="{Binding Path=Name}"/>
<TextBlock Text="{Binding Path=Path}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid Width="786">
<Button Height="23" HorizontalAlignment="Right" Margin="0,24,166,0" Name="btnTest" VerticalAlignment="Top" Width="75" Click="btnTest_Click">Add</Button>
<ComboBox StaysOpenOnEdit="True" DropDownClosed="comboBox1_DropDownClosed" PreviewTextInput="comboBox1_PreviewTextInput" SelectionChanged="comboBox1_SelectionChanged" ItemTemplate="{StaticResource ShowResult}" Margin="259,109,22,89" Name="comboBox1" IsEditable="True" />
<ContentControl Height="50" Margin="268,0,22,21" Name="contentControl1" VerticalAlignment="Bottom" Content="{Binding ElementName=comboBox1,Path=SelectedValue}" ContentTemplate="{StaticResource ShowResult}"/>
</Grid>
You got the binding part right - binding to the data and using a DataTemplate to display the source the way you want to.
As to your second question, a way to do it would be to use a ComboBox with IsEditable="True" as you have, and withing the TextChanged event handler check if the comboBox.Items contains the new value, if not check use Linq to seach for a match:
if (comboBox.Items.Contains(e.NewValue))
return;
var matches =
with comboBox.Items
select item
where item.BeginsWith(e.NewValue);
if (matches.Count > 0)
comboBox.SelectedItem = matches.First();
Just place the Property Binding expression to the textBox,You dont need to apply template.
Another way to get exact Data template, Place a ContentControl in the place of textBox and assign the same DataTemplate (say x:Name="robinTemplate")
<ContentControl Content="{Binding ElementName=cmbBox,Path=SelectedValue}" ContentTemplate="{StaticResource robinTemplate}"/>
For making the Selected content display in the same way :
Create a copy of the combobox control template and you will find a ContentPresenter there. Replace that with the ContentControl.. This is not the right solution though.