How to binding textbox to the list - c#

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}"/>

Related

WPF MVVM - ComboBox binding selected value

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}

How send to combobox 1 property from object

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"/>

Binding ComboBox item to string

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}"/>

C# WPF Combobox select first item

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! :)

Binding from Different Selected Listbox Items

*Intro: *
I'm working with a standard MVVM framework and I have two listboxes from which I want to be able to select one item from. The listboxes are binding to different ObservableCollections of the same class.
After binding to the ViewModel, I want to be able to represent the selected Item on the same window, from either of the Listbox depending on which item I am selecting.
ViewModel -
private KisesaSearchResultViewModel _selectedPerson;
public KisesaSearchResultViewModel SelectedPerson
{
get
{
return _selectedPerson;
}
set
{
_selectedPerson = value;
OnPropertyChanged("SelectedPerson");
}
}
private KisesaSearchResultViewModel _selectedSearch;
public KisesaSearchResultViewModel SelectedSearch
{
get
{
return _selectedSearch;
}
set
{
_selectedSearch = value;
SelectedPerson = value;
OnPropertyChanged("SelectedSearch");
}
}
private KisesaSearchResultViewModel _selectedMatch;
public KisesaSearchResultViewModel SelectedMatch
{
get
{
return _selectedMatch;
}
set
{
_selectedMatch = value;
SelectedPerson = _selectedMatch;
OnPropertyChanged("SelectedMatch");
}
}
XAML -
<ListBox ItemsSource="{Binding Path=MatchedMembers, Mode=OneWay}"
ItemTemplate="{StaticResource SearchResult}"
SelectedItem="{Binding SelectedSearch}">
</ListBox>
<ListBox ItemsSource="{Binding Path=SelectedMatchList, Mode=OneWay}"
ItemTemplate="{StaticResource SearchResult}"
SelectedItem="{Binding SelectedMatch}">
</ListBox>
I want to display information as such:
<TextBlock Grid.Row="1" Text="{Binding Path= SelectedPerson.FullName}" FontSize="18" FontWeight="Bold" Style="{StaticResource PInfo}" />
<TextBlock Grid.Column="0" Grid.Row="2" Style="{StaticResource Info}" Margin="30,0,0,0" Text="{Binding Path=SelectedPerson.Age}"/>
Question:
I need to have SelectedSearch and SelectedPerson because I want to be able to change SelectedPerson independtly. At this point, the SelectedPerson is getting set by the SelectedSearch setter, but it is not binding to the Textblocks. I am using OnPropertyChanged, but do I need to do something else like use an Event Handler? Also, slightly unrelated, but can I restrict a WPF window so that only one item from two different Listboxes is selected at a time?

Categories

Resources