I write this combobox
<ComboBox
x:Name="ComboBoxRole"
SelectedItem="{Binding ApplicationModel.CategoryName}"
ItemsSource="{Binding Categories}"
Style="{StaticResource ComboBoxStyle}" Text="Choose"
/>
for this model
public class CategotyModel : INotifyPropertyChanged, IDataErrorInfo
{
private string id;
private string name;
public string Id
{
get => id;
private set
{
id = value;
NotifyPropertyChanged("Id");
}
}
public string Name
{
get => name;
private set
{
name = value;
NotifyPropertyChanged("Name");
}
}
}
for Item source create this property
public IList<CategotyModel> Categories
{
get
{
var categoriesDTO = _categoryManager.GetAllCategories();
this.categories = mapper.DefaultContext.Mapper.Map<IList<CategotyModel>>(categoriesDTO);
return categories;
}
}
it work fun, but I don't know how sent to combo just 1 parametre , because I take "AppStore.WPF.MVVMLight.Models.CategotyModel" object.
Note: I take the result from server. it's never mind.
(without foreach the IList<CategoryModel> and write to list of the string - i think it's bad way).
Edit
<ComboBox
x:Name="ComboBoxRole"
SelectedItem="{Binding ApplicationModel.CategoryName}"
SelectedValuePath="Name"
DisplayMemberPath="Name"
ItemsSource="{Binding Categories}"
Style="{StaticResource ComboBoxStyle}"
Text="Choose"
/>
You need to fix a few things in your ComboBox: To display the Name properties of the items, add DisplayMemberPath="Name". To select just the name property of the selected item instead of the whole object, add SelectedValuePath="Name", and bind ApplicationModel.CategoryName to SelectedValue instead of SelectedItem.
SelectedItem will still be the whole object, even when SelectedValuePath is in use.
<ComboBox
x:Name="ComboBoxRole"
SelectedValue="{Binding ApplicationModel.CategoryName}"
SelectedValuePath="Name"
DisplayMemberPath="Name"
ItemsSource="{Binding Categories}"
Style="{StaticResource ComboBoxStyle}"
Text="Choose"
/>
you want DisplayMemberPath="Name"
<ComboBox
x:Name="ComboBoxRole"
DisplayMemberPath="Name"
SelectedItem="{Binding ApplicationModel.CategoryName}"
ItemsSource="{Binding Categories}"
Style="{StaticResource ComboBoxStyle}"
Text="Choose"/>
Related
EDIT
Solution was actually a proper setting of SelectedItem, SelectedValue and SelectedValuePath properties.
<ComboBox
Grid.Column="1"
Padding="5"
DisplayMemberPath="PositionName"
IsSynchronizedWithCurrentItem="False"
ItemsSource="{Binding Positions, Mode=OneWay}"
SelectedItem="{Binding SelectedOperatorPosition, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"
SelectedValue="{Binding SelectedOperatorPosition.PositionName}"
SelectedValuePath="PositionName" />
QUESTION
I am trying to bind ComboBox SelectedValue with DataGrid SelectedItem using MVVM pattern.
ComboBox ItemSource is Shifts property. I want it's SelectedValue to be bound with SelectedShift property, which is updated each time user selects another OperatorModel from DataGrid.
Although SelectedOperator setter sets SelectedShift value to SelectedOperator.Shift, ComboBox doesn't get updated.
View
Debugging ViewModel Property setter
My ViewModel:
private Operator selectedOperator;
public Operator SelectedOperator
{
get
{
return selectedOperator;
}
set
{
selectedOperator = value;
if (selectedOperator != null)
{
SelectedShift = selectedOperator.Shift;
}
OnPropertyChanged(nameof(SelectedOperator));
}
}
private Shift selectedShift;
public Shift SelectedShift
{
get
{
return selectedShift;
}
set
{
selectedShift = value;
OnPropertyChanged(nameof(SelectedShift));
}
}
XAML:
<ComboBox
Grid.Column="1"
Padding="5"
DisplayMemberPath="Name"
ItemsSource="{Binding Shifts}"
SelectedValue="{Binding SelectedShift}"
SelectedValuePath="Name" />
i think you should use SelectedItem="{Binding SelectedShift}
I have a listbox and a textbox, I want the textbox show data according to the listbox selection. The problem is I already have the listbox binding to an object like this:
<ListBox x:Name = "listbox" SelectionMode="Single" ItemsSource="{Binding Products}" SelectedItem="{Binding SelectedProduct}" DisplayMemberPath="{Binding SelectedProduct}">
The textbox which I want to populate data is not the property of SelectedProduct that I binding to, it only has relation to the listbox index. For example:
private int[] _InputStartAddress = new int[20];
textbox.text = _InputStartAddress[listbox.SelectedIndex];
The ViewModel of SelectedProduct:
private Product selectedProduct;
public Product SelectedProduct
{
get { return selectedProduct; }
set
{
if (selectedProduct != value)
{
selectedProduct = value;
NotifyPropertyChanged();
}
}
}
What should I do to achieve this?Thanks!
bind directly to ListBox property using ElementName:
<ListBox Name="ListProducts" SelectionMode="Single" ItemsSource="{Binding Products}" SelectedItem="{Binding SelectedProduct}" DisplayMemberPath="{Binding SelectedProduct}">
<TextBox Text="{Binding Path=SelectedIndex, ElementName=ListProducts}"/>
I want to bind a ComboBox item to a string, but it does not work. My code is below.
Code in view:
<ComboBox
SelectedValuePath="content"
SelectedItem="{Binding ProductName}"
......
<ComboBoxItem>1111111111</ComboBoxItem>
<ComboBoxItem>2222222222222</ComboBoxItem>
<ComboBoxItem>333333333333</ComboBoxItem>
</ComboBox>
Code in view model:
private string _productName;
public string ProductName
{
get { return _productName; }
set
{
if (_productName != value)
{
_productName = value;
RaisePropertyChangedEvent("ProductName");
}
}
}
I assume you want to get the text from the ComboboxItem and not the ComboBoxItem iteself.
So you are binding the wrong information. This should work.
<ComboBox
SelectedValuePath="content"
Text="{Binding ProductName}"
......
<ComboBoxItem>1111111111</ComboBoxItem>
<ComboBoxItem>2222222222222</ComboBoxItem>
<ComboBoxItem>333333333333</ComboBoxItem>
</ComboBox>
Selected Item is of type ComboBoxItem, it will not accept String.
If you want to display product name in some other place try maybe something like this:
<TextBox Text="{Binding ElementName=my_ComboBox, Path=SelectedItem}"/>
Just a suggestion.
You already use a binding for the SelectedItem, why don't you set up another binding for the Items using the ItemsSource? So you would not need to add them statically in your view.
In addition you would not have the trouble to wonder whether you deal with instances of ComboxItem or String with your SelectedItem binding.
In case of the binding via ItemsSource you can be sure that the SelectedItem is a string.
Here is the code:
<ComboBox
SelectedValuePath="content"
SelectedItem="{Binding ProductName}"
ItemsSource="{Binding ProductNames}"
</ComboBox>
In your view model (or code behind) you define the ProductNames:
public String[] ProductNames
{
get
{
return _productNames;
}
set
{
if (_productNames!= value)
{
_productNames = value;
RaisePropertyChangedEvent("ProductNames");
}
}
}
String[] _productNames;
public NameOfConstructor()
{
List<String> productNames = new List<String>();
productNames.Add("A");
productNames.Add("B");
productNames.Add("C");
ProductNames = productNames.ToArray();
}
If it was possible that the list of names changes during execution, I would use a ObservableCollection<string> instead String[].
It should be like this
Create an observable collection of Product in View Model. Lets Say ProductCollection
Bind to the ComboBox ItemSource as given below
<ComboBox Name="productComboBox" Width="200" Height="30" ItemsSource="{Binding ProductCollection}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=ProductName}"></TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
if you want to show in textbox somewhere
use this
<TextBox Text="{Binding ElementName=productComboBox, Path=SelectedItem}"/>
Goodday,
I want my combobox to select the first item in it. I am using C# and WPF. I read the data from a DataSet. To fill the combobox:
DataTable sitesTable = clGast.SelectAll().Tables[0];
cbGastid.ItemsSource = sitesTable.DefaultView;
Combo box XAML code:
<ComboBox
Name="cbGastid"
ItemsSource="{Binding}"
DisplayMemberPath="Description"
SelectedItem="{Binding Path=id}"
IsSynchronizedWithCurrentItem="True" />
If I try:
cbGastid.SelectedIndex = 0;
It doesn't work.
Update your XAML with this:
<ComboBox
Name="cbGastid"
ItemsSource="{Binding}"
DisplayMemberPath="Description"
SelectedItem="{Binding Path=id}"
IsSynchronizedWithCurrentItem="True"
SelectedIndex="0" /> // Add me!
Try this, instead of SelectedIndex
cbGastid.SelectedItem = sitesTable.DefaultView.[0][0]; // Assuming you have items here.
or set it in Xaml
<ComboBox
Name="cbGastid"
ItemsSource="{Binding}"
DisplayMemberPath="Description"
SelectedItem="{Binding Path=id}"
IsSynchronizedWithCurrentItem="True"
SelectedIndex="0" />
It works for me if I add a SelectedIndex Property in my VM with the proper binding in the xaml. This is in addition to the ItemSource and the SelectedItem. This way SelectedIndex defaults to 0 and I got what I wanted.
public List<string> ItemSource { get; } = new List<string> { "Item1", "Item2", "Item3" };
public int TheSelectedIndex { get; set; }
string _theSelectedItem = null;
public string TheSelectedItem
{
get { return this._theSelectedItem; }
set
{
this._theSelectedItem = value;
this.RaisePropertyChangedEvent("TheSelectedItem");
}
}
And the proper binding in the xaml;
<ComboBox MaxHeight="25" Margin="5,5,5,0"
ItemsSource="{Binding ItemSource}"
SelectedItem="{Binding TheSelectedItem, Mode=TwoWay}"
SelectedIndex="{Binding TheSelectedIndex}" />
Update your XAML with this code :
<ComboBox
Name="cbGastid"
ItemsSource="{Binding}"
DisplayMemberPath="Description"
SelectedItem="{Binding Path=id, UpdateSourceTrigger=PropertyChanged, Mode=OneWayToSource}"
IsSynchronizedWithCurrentItem="True" />
Hope it works :)
Try this,
remove from de C# code the following line:
cbGastid.ItemsSource = sitesTable.DefaultView;
and add this:
cbGastid.DataContext = sitesTable.DefaultView
Try this..
int selectedIndex = 0;
cbGastid.SelectedItem = cbGastid.Items.GetItemAt(selectedIndex);
XAML Code:
<ComboBox
Name="cbGastid"
ItemsSource="{Binding}"
DisplayMemberPath="Description"
SelectedItem="{Binding Path=id}"
IsSynchronizedWithCurrentItem="True" />
This works for me... Given an Authors and Books table with a one-to-many relationship. The XAML Looks like this:
<ComboBox DisplayMemberPath="AuthorName" ItemsSource="{Binding Authors}" Name="ComboBoxAuthors"
SelectedItem="{Binding SelectedAuthor}"
IsSynchronizedWithCurrentItem="True" Grid.Row="0" Grid.Column="0"/>
<ComboBox DisplayMemberPath="BookTitle" ItemsSource="{Binding Books}" Name="ComboBoxBooks"
SelectedItem="{Binding SelectedBook}"
IsSynchronizedWithCurrentItem="True" Grid.Row="0" Grid.Column="1" />
Then my ViewModel looks like this:
enter public class MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
BooksEntities ctx = new BooksEntities();
List<Author> _authors;
List<Book> _books;
Author _selectedAuthor;
Book _selectedBook;
public MainViewModel()
{
FillAuthors();
}
public List<Author> Authors
{
get { return _authors; }
set
{
_authors = value;
NotifyPropertyChanged();
if (_authors.Count > 0) SelectedAuthor = _authors[0]; // <--- DO THIS
}
}
public Author SelectedAuthor
{
get { return _selectedAuthor; }
set
{
_selectedAuthor = value;
FillBooks();
NotifyPropertyChanged();
}
}
public List<Book> Books
{
get { return _books; }
set
{
_books = value;
NotifyPropertyChanged();
if (_books.Count > 0) SelectedBook = _books[0]; // <--- DO THIS
}
}
public Book SelectedBook
{
get { return _selectedBook; }
set
{
_selectedBook = value;
NotifyPropertyChanged();
}
}
#region Private Functions
private void FillAuthors()
{
var q = (from a in ctx.Authors select a).ToList();
this.Authors = q;
}
private void FillBooks()
{
Author author = this.SelectedAuthor;
var q = (from b in ctx.Books
orderby b.BookTitle
where b.AuthorId == author.Id
select b).ToList();
this.Books = q;
}
#endregion
}
Take a look at the Authors and Books properties of the ViewModel class. Once they are set, the usual PropertyChanged event is raised and the SelectedAuthor / SelectedBook is set to the first item.
Hope this helps.
Let me share my solution, that worked for me after several trials.
Here is my combo box:
<ComboBox
Name="fruitComboBox"
ItemsSource="{Binding Fruits}"
SelectedIndex="0"
SelectedValue="{Binding ComboSelectedValue}"
IsSynchronizedWithCurrentItem="True">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding displayFruitName}"
CommandParameter="{Binding SelectedValue, ElementName=fruitComboBox}"/>
</i:EventTrigger>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding displayFruitName}"
CommandParameter="{Binding SelectedValue, ElementName=fruitComboBox}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
In my case, I had to invoke a command every time a new item was selected in the comboBox or when the itemsource was being updated. But, the element at zero index was not getting selected when the item source was updated. So, what did I do? I added:
IsSynchronizedWithCurrentItem="True"
in the comboBox properties. It did the trick for me.
A little code from my ViewModel is below:
/// item source for comboBox
private List<string> fruits = new List<string>();
public List<string> Fruits
{
get { return fruits; }
set
{
fruits = value;
OnPropertyChanged();
ComboSelectedValue = value[0];
}
}
// property to which SelectedValue property of comboxBox is bound.
private string comboselectedValue;
public string ComboSelectedValue
{
get { return comboselectedValue; }
set
{
comboselectedValue = value;
OnPropertyChanged();
}
}
You can refer to this stackoverflow link and msdn link for further clarification regarding IsSynchronizedWithCurrentItem="True"
Hope it Helps! :)
I have this column/code in my DataGrid:
<sdk:DataGridTemplateColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Width="Auto" Header="Province/State">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=SelectedProvince.ProvinceName, Mode=OneWay}"/>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
<sdk:DataG ridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Path=ProvinceList, Mode=TwoWay}"
SelectedItem="{Binding Path=SelectedProvince, Mode=TwoWay}"
DisplayMemberPath="ProvinceName" />
</DataTemplate>
</sdk:DataGridTemplateColumn.CellEditingTemplate>
</sdk:DataGridTemplateColumn>
Then this is the code behind(I have cut out the unrelated code):
public class BatchSeedingAddressVM : ViewModelBase
{
public BatchSeedingAddressVM()
{
_saveAddressButtonCommand = new RelayCommand(SaveAddressButtonCommand_OnExecute);
CreateJurisdictionList();
}
public BatchSeedingAddressVM(int? batchSeedingAddressOID, string address1, string address2, string city, string postalCode, string province2Code)
{
_saveAddressButtonCommand = new RelayCommand(SaveAddressButtonCommand_OnExecute);
CreateJurisdictionList();
BatchSeedingAddressOID = batchSeedingAddressOID;
Address1 = address1;
Address2 = address2;
City = city;
PostalCode = postalCode;
//SelectedProvince2Code = province2Code;
SelectedProvince = _provinceList.Where(x => x.Province2Code == province2Code).FirstOrDefault();
}
private ObservableCollection<Province> _provinceList = new ObservableCollection<Province>();
public ObservableCollection<Province> ProvinceList
{
get
{
return _provinceList;
}
set
{
if (_provinceList != value)
{
_provinceList = value;
RaisePropertyChanged("ProvinceList");
}
}
}
private Province _selectedProvince;
[Display(Name = "Province")]
public Province SelectedProvince
{
get
{
return _selectedProvince;
}
set
{
if (_selectedProvince != value && value != null)
{
_selectedProvince = value;
RaisePropertyChanged("SelectedProvince");
}
}
}
}
Here is the issue: the DataGrid cell has 2 templates: CellTemplate and CellEditingTemplate. When the CellTemplate is active the textbox in it picks up the SelectedProvince as planned and displays the name of the province. The problem is that when CellEditingTemplate becomes active the ComboBox in it does not pick up the (default)SelectedItem value and displays an empty box.
Is there something I am missing? How the binding has to be setup so that it would be possible to set the default SelectedItem in the combobox in CellEditingTemplate?
Thanks much in advance!
I think TwoWay binding for ItemsSource can be the problem.
ItemsSource="{Binding Path=ProvinceList, Mode=TwoWay}"
I suggest to change it to OneTime or OneWay depending on your design.
I might be wrong, but I think that if you're using SelectedValuePath, you need to use SelectedValue instead of SelectedItem, so change this:
SelectedItem="{Binding Path=SelectedProvince, Mode=TwoWay}"
to this:
SelectedValue="{Binding Path=SelectedProvince, Mode=TwoWay}"