i'm new to WPF. I have an application with multiple tabs. In one tab I can insert data into a table in the database. In another tab I have a combobox with itemsource of the table mentioned earlier. I want to update the combobox items when user want to chose from the combobox./
I tried with the GotFocus property in the following way:
private void ComboBoxOperatingPoints_GotFocus_1(object sender, RoutedEventArgs e)
{
this.ThisViewModel.UpdateModel();
}
Updatemodel function contains the following:
this.OperatingPoints = new ObservableCollection<Operating_Point>(new OperatingPointRepository().GetAll());
this.NotifyPropertyChanged("OperatingPoints");
The combobox bindind in the XAML :
<ComboBox SelectionChanged="ComboBoxOperatingPoints_SelectionChanged"
x:Name="ComboBoxOperatingPoints"
GotFocus="ComboBoxOperatingPoints_GotFocus_1"
FontSize="30"
HorizontalAlignment="Right"
Margin="40,40,0,0"
VerticalAlignment="Top"
Width="200"
Height="50"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding OperatingPoints}"
DisplayMemberPath="name"
SelectedValue="{Binding OperatingPointID,UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="operating_point_id"
>
The combobox refresh, but gives validation error and I can't use it anymore after the first GotFocus event occured.
Thanks in advance!
EDIT:
Finaly I changed the GotFocus event to DropDownOpened event and it's working fine.
Your code is creating a new ObservableCollection on every update. You probably only want to create the ObservableCollection once, then replace it's contents in UpdateModel. So, for example, in your view model's constructor, instantiate the OperatingPoints collection:
public class MyViewModel {
public MyViweModel() {
this.OperatingPoints = new ObservableCollection<Operating_Point>();
}
}
Then, in UpdateModel:
public void UpdateModel() {
this.OperatingPoints.Clear();
foreach ( Operating_Point point in new OperatingPointRepository().GetAll() ) {
this.OperatingPoints.Add(point);
}
NotifyPropertyChanged( "OperatingPoints" );
}
Related
I am attempting to bind a list to a combobox. I want to display this list of options within the Combobox itself. (Later to allow the user to select an item 'SelectedItem', I'll cross that bridge when I get there)
MyCode.cs
// List of values for 'Type' dropdown
private static readonly List<string> MarkerTypeList = new List<string>(new string[]
{
"Analog",
"Digital"
});
// Binding for viewing list in window
public List<string> TypeOptions
{
get { return MarkerTypeList; }
}
MyCode.xaml
<ComboBox x:Name="myCombobox" HorizontalAlignment="Left" Margin="125,26,0,0" VerticalAlignment="Top" Width="70" Height="23" SelectedItem="" ItemsSource="{Binding TypeOptions}" />
The solution boiled down to changing this:
ItemsSource="{Binding TypeOptions}"
to this:
ItemsSource="{Binding Marker.TypeOptions}"
Thanks for the input, sorry you didnt have a whole lot to go on.
If you bind you should have your INotifyPropertyChanged interface added to your class which is the actual ViewModel for your ComboBox.
So - 1. Add the Interface to the class. 2. Create RaisePropertyChanged function. 3. Call the function through the setter of the property. This will push the updated value of the property through the binding and you will see the combobox populated.
I want to populate a ComboBox based on selection of other ComboBox.
Both combo boxes are populate from database using WCF.
My problem is that on first selection it's not working (just after second selection it's work and it's show results from first selection).
XAML
<ComboBox
x:Name="selClientCombo"
SelectionChanged="listEchipamente"
IsEditable="True"
SelectedIndex="-1"
HorizontalAlignment="Left"
Margin="455,35,0,0"
VerticalAlignment="Top"
Width="215"
ItemsSource="{Binding Mode=OneWay}"/>
<ComboBox
x:Name="selEchipamentCombo"
HorizontalAlignment="Left"
Margin="457,65,0,0"
VerticalAlignment="Top"
Width="213"
ItemsSource="{Binding}"/>
code
private void listEchipamente(object sender, SelectionChangedEventArgs e)
{
List<string> echipamenteWCF = client.getEchipament(selClientCombo.Text).ToList();
MessageBox.Show(" Client Selected !");
if (selEchipamentCombo.Items.Count >0)
{
selEchipamentCombo.Items.Clear();
}
for (int i = 0; i < echipamenteWCF.Count(); i++)
{
selEchipamentCombo.Items.Add(echipamenteWCF[i]);
}
}
At the time SelectionChanged is fired, the Text has not been updated (and hence it holds the previous value).
You should access the underlying data item to get the Text instead:
if(selClientCombo.SelectedItem == null) return;
List<string> echipamenteWCF =
client.getEchipament(selClientComo.SelectedItem.ToString()).ToList();
...
I supposed the ToString() will resolve the display Text. You can always cast SelectedItem to the actual type and access its string property (being shown as Text) easily. You can also access the SelectedValue with condition that some SelectedValuePath is set for the ComboBox.
I want when a user selects one or multiple items that my source property gets updated. I have tried with the binding mode OneWayToSource but this is not helping. Below is the XAML and ViewModel code:
<ListBox x:Name="ItemsListBox" SelectionMode="Multiple" Height="300"
ItemsSource="{Binding ResultSet}"
SelectedItem="{Binding SelectedItems,Mode=OneWayToSource}">
private List<string> _selectedItems;
public List<string> SelectedItems
{
get
{
return _selectedItems;
}
set
{
_selectedModeItems = value;
NotifyPropertyChanged("SelectedItems");
}
}
I have taken the approach by using Attached behaviours and it works , but is there any simpler way?
Your question should be like this.
How to get multiple selected items from the ListBox in WPF with MVVM?
Well, you have the answer from following stackoverflow threads.
link 1
link 2
Simply you can define IsSelected property in your ResultSet view model. Then if you want to get selected items at any point, just get the items which the "IsSelected" property is set to true from the ResultSet.
you could also create an Attached Behavior
here is an Example how to do it
WPF ListBox has two properties related to the currently selected item:
SelectedItem available for binding, bound to the first selected item.
SelectedItems (with an 's' at the end) is not available to binding.
When multi selection is enabled, you want to have access to SelectedItems but unfortunately you can't bind to it
You can workaround this limitation using code behind.
Create a property named SelectedItems that will contain the selection, then subscribe the SelectionChanged event:
<ListBox x:Name="ItemsListBox" SelectionMode="Multiple" Height="300"
ItemsSource="{Binding ResultSet}"
SelectionChanged="ListBox_SelectionChanged">
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (string item in e.RemovedItems)
{
SelectedItems.Remove(item);
}
foreach (string item in e.AddedItems)
{
SelectedItems.Add(item);
}
}
I have a ListBox called NotesList. I have an ObservableCollection called noteList, and I have a TextBox called NoteContents.
In my ObservableCollection, I set the Filename and Contents properties for a few items and then it gets added (bound) to my ListBox.
But now, I want to (when I click a button), show the "Contents" of the ListBox Item that was selected in the NoteContents TextBox.
How can I do this?
I currently have:
private void NotesList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
NoteContents.Text = noteList.Where(x => x.Filename.Contains(NotesList.SelectedValue.ToString())).FirstOrDefault().Contents;
}
You can do this without button clicks, just binding like:
<ListBox Name="NotesList" ItemsSource="{Binding YourObservableCollection}">
<!--Your bindings here-->
</ListBox>
<TextBox Text="{Binding ElementName=NotesList, Path=SelectedItem.Contents}" />
I'm trying to initiate an action based on a selection in a ComboBox I created in WPF. I'm pretty new to WPF and C#. My ComboBox has
<ComboBox x:Name="SampleComboBox" Width="100" ItemsSource="{Binding Path=NameList}" />
Where NameList is a List property in the code behind. Now I want to generate an action based on the selection in the ComboBox and not sure where to start. Thanks.
You'll need to add a method to handle the SelectionChanged event. You can either do this in code:
this.MyComboBox.SelectionChanged += new SelectionChangedEventHandler(OnSelectionChanged);
or in XAML:
<ComboBox x:Name="SampleComboBox" Width="100"
ItemsSource="{Binding Path=NameList}" SelectionChanged="OnSelectionChanged" />
where you can then do something with the selected items:
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBoxItem cbi = (ComboBoxItem) (sender as ComboBox).SelectedItem;
}
You can get the selected object by writing SampleComboBox.SelectedItem.
This will return an instance of an item in your source list.
Are these a finite set of values in this NameList that is the ItemsSource for this?
Why not amend that xaml to read:
<ComboBox x:Name="SampleComboBox" Width="100" SelectedItem="{Binding TheItem}" ItemsSource="{Binding Path=NameList}" />
and then in your ViewModel for this, have something like:
public static readonly DependencyProperty TheItemProperty=
DependencyProperty.Register("TheItem", typeof(string), typeof(OrderEditorViewModel),
new PropertyMetadata((s, e) => {
switch (e.NewValue) {
case "SomeValue":
// Do something
break;
case "SomeOtherValue":
// Do another thing
break;
default:
// Some default action
break;
}
}));
public string TheItem{
get { return (string)GetValue(TheItemProperty); }
set { SetValue(TheItemProperty, value); }
}
You can do your actions based on the selection in that switch statement which will be invoked whenever the selection is changed.