When I use ComboBox or other controls that have ItemsSource and SelectedItem property bindings then each time upon the initial binding during runtime and also each time when the bound collection to ItemsSource changes I experience that the content of bound SelectedItem object is changed.
How can I disable this?
For example:
I have <ComboBox MinWidth="300" ItemsSource="{Binding AvailableMasters}" SelectedItem="{Binding SelectedMaster}">
When I run the application the SelectedMaster property is assigned the first item in AvailableMasters. Also, each time the AvailableMasters collection changes (for example, by assigning a new collection to the property) the SelectedMaster is again adjusted.
The desired behavior is that SelectedItem (SelectedMaster) is only populated/changed when the end-user clicks with the mouse on that item / chooses that item from the ComboBox or other control.
Set a flag/bool property before you update the collection and use it in SelectedMaster property. Or do you need only XAML solution?
Related
I have a WPF control inheriting from ComboBox whose ItemsSource is bound to a list of elements, and whose SelectedItem is bound to another field. I have two references to the same list in my application: one resides in my MainWindow class, and one resides in my App class.
The list of elements used as the ItemsSource is assigned to the ComboBox at the time it is created. Thus, I expect to get an ItemsSourceChanged event.
The strange thing is, if the ItemsSource is bound to the MainWindow's list, then the ComboBox becomes populated with the correct SelectedItem drawn from the bound field. However, if I bind the ItemsSource to the App's copy of the list, then the SelectedItem becomes overwritten with null due to the ItemsSourceChanged event.
Here is the XAML for the ComboBox when it's binding to the App copy of the list:
<local:TagSelectionComboBox FilteredTagsList="{Binding Path=TagsList, Source={x:Static Application.Current}}" SelectedItem="{Binding TagValue}"></local:TagSelectionComboBox>
Here is the XAML for the ComboBox when it's binding to the MainWindow copy of the list:
<local:TagSelectionComboBox FilteredTagsList="{Binding TagsList, RelativeSource={RelativeSource AncestorType=Window}}" SelectedItem="{Binding TagValue}"></local:TagSelectionComboBox>
Here is the MainWindow's property used for binding:
public ObservableCollection<Tag> TagsList
{
get { return proj.Sim.Tags; }
}
And here is the App's property used for binding:
public ObservableCollection<Tag> TagsList
{
get { return proj.Sim.Tags; }
}
So these two properties on App and MainWindow are returning the same list. Stepping through in the debugger confirms: proj.Sim.Tags contains the same list in both cases.
Why does changing from one binding source to another alter the binding behavior? Is something else going on?
I've found that if I explicitly set IsSynchronizedWithCurrentItem="True", then the behavior is the same in both cases. So it's almost like IsSynchronizedWithCurrentItem="True" is the default behavior when I use the MainWindow (RelativeSource) binding but IsSynchronizedWithCurrentItem="False" is the default behavior when I use the App (x:Static) binding.
Background: the ComboBox-derived control in this question is basically the same as YantingChen's answer for this question:
Dynamic filter of WPF combobox based on text input
about to add the following features
If select this combobox, I want to change the itemssource of the datagrid.
Are there any examples related to this?
You can do the following:
Create a WPF project.
Create a view (xaml) with the combobox and datagrid inside it.
Create a view model for this newly created view and declare public properties (collection/list) for the ItemsSource of the combobox and the grid. Also have a property for the selected item of the combobox.
Set this view model as the data context of your view.
In the setter of the combobox's selected item - change the property which is bound to the datagrid's ItemsSource to the collection that you by calling a method or however you wish.
I did this:
Add the namespace for caliburn in xaml
xmlns:cal="http://www.caliburnproject.org"
Here is the combobox:
<ComboBox ItemsSource="{Binding ComboBoxItemSource}" SelectedItem="{Binding SelectedItem}" cal:Message.Attach="[Event SelectionChanged] = [ComboBoxSelectionChanged()]" />
and the viewmodel should be having this method:
public void ComboBoxSelectionChanged()
{
// here based on the SelectedItem you can change the ItemSource for the dataGrid.
}
Whenever you are changing the selectedItem of Combobox the method will get hit and based on the logic that you need you can assign the ItemSource for the dataGrid.
Hope this helps :)
I've bound a ComboBox to my TextBox
<TextBlock Grid.Row="1" Name="DescriptionText" Text="{Binding ElementName=ScreenLocations, Path=SelectedItem.Description}" />
I have 4 ComboBoxes in my grid. What I want to do is, every time I select an item from any ComboBox, update the TextBox with the selected objects Description property.
Is it possible to bind multiple ComboBoxes to one TextBox, or would I need to use an event of some sort?
Create a property in your ViewModel and bind all your comboboxes' 'selectedItem' property to it (Use Mode="OneWayToSource", this will prevent changes on selectedItem of one ComboBox to affect the other), then bind your TextBox to the same property created in the VM with Mode="OneWay". Don't forget to implement INotifyPropertyChanged in your VM.
I am looking for a way where a control can be enable when an item from a combo box is selected. Is there a simple way through data binding when a user selects an item from a combo box that it then enables another control to be used?
If you're using MVVM, you can bind the SelectedItem of the combobox to a property in your viewmodel.
Say this is your combobox:
<ComboBox ItemsSource="{Binding widgetlist}" SelectedItem="{Binding Path=selectedwidget, Mode=TwoWay}"></ComboBox>
And this is your control:
<DockPanel IsEnabled="{Binding controlenabled}">
...
</DockPanel>
Then in selectedwidget's setter, you can change the controlenabled property to False or True. Don't forget to notify that the controlenabled property changed (or if you want, make controlenabled a DependencyProperty.)
In summary, you've got 3 properties to bind to:
widgetlist, an ObservableCollection or some other collection that is the source for your combobox
selectedwidget, an item of that collection type that changes to whatever the combobox currently has selected
controlenabled, a bool that the other controls look at to decide if they are enabled/disabled.
Like many examples in MVVM, this way may require slightly more thought and code on the outset, but will be far more maintainable and scalable later. For example, say you want some more controls to also enable/disable themselves based on the same scenario. Piece of cake: add IsEnabled="{Binding controlenabled}"> to them.
Yes. You want to bind to IsEnabled in the target control which you want to dynamically enable or disable, and use a Value Converter to convert a matching string or item from the ComboBox to a true value for being enabled.
Tell me it ain't so.
I have a typical windows/file explorer like setup.
Left Side I have a TreeView all data bound showing nodes in a hierachy
Right Side I have a ListView showing Node.Properties
ListView has a IsSynchronizedWithCurrentItem property, which rocks. e.g. If I had another ListView showing a list of nodes and both listViews have this property set to true. Changing selection of node in NodesListView will update the PropertiesListView automatically.
Now I need the same thing with a NodesTreeView and a PropertiesListView... and seems like TreeView has no such property.
Is there a more 'the WPF way' kind of solution to this problem ? Or do I have to handle the NodeSelectionChanged event of the Tree and refresh the listView via code.
A really simple solution is to bind your "details" UI elements to the SelectedValue property of the TreeView. For example, if your TreeView looked like this:
<TreeView Name="CategoryName" ItemsSource="{Binding Source={StaticResource A_Collection}, Path=RootItems}" />
Then you could bind details UI elements (like a textbox) using:
<TextBox Text="{Binding ElementName=CategoryTreeView, Path=SelectedValue.Name}"/>
Would cause the text box to be bound to Name property of the items currently selected in the TreeView.
If you want to bind many UI items as details for the selected TreeView item, consider setting up a DataContext on the elemtent that contains all the details controls (DockPanel / Grid / StackPanel, etc).
<ListView Name="listView1"
ItemsSource="{Binding Path=SelectedItem.Modules,
ElementName=treeView1, Mode=OneWay}"
IsSynchronizedWithCurrentItem="True">
Where ".Modules" is the collection of child items off the selected treeview item you want to display. Don't worry about wiring up the "SelectedItemChanged" event on the treeview.
Why exactly it doesn't implement the property, I do not know, but i have a suggestion down below.
Your code above will work, however, it is not what the IsSynchronizedWithCurrentItem property does. Any ItemsControl binds to the ICollectionView of the ItemsSource property. To get that ICollectionView, we can call CollectionViewSource.GetDefaultCollectionView(object o). Depending on the type of object o, you get a different concrete implementation of the ICollectionView inteface. CollectionView and ListCollectionView are two concrete classes that come to mind.
The ICollectionView interface contains a member called CurrentItem. What the IsSynchronizedWithCurrentItem does is: whenever an item is clicked on the ItemsControl, it sets the CurrentItem for the collection view. The ICollectionView also has two events: CurrentItemChanging and CurrentItemChanged. When the IsSynchronizedWithCurrentItem property is set, the ItemsControl will update the SelectedItem based on what the ICollectionView's CurrentItem is. Makes sense?
In master/detail WPF scenarios, we simply are binding to ICollectionViews and their CurrentItem (the CurrentItem syntax is something like {Binding Items/Name}, where Name is the Name property on the collection's CurrentItem.
So although your code works for your purposes, it doesn't do what that property does. To do what the property does, you need to do the following:
When an item is selected, you need to figure out which collection it belongs to. How do we do this? I believe this is why TreeView doesn't implement it. The selected item is displayed in a TreeViewItem. The DataContext is the object itself, but what is the parent collection ? I guess to get it you could either cache it in some hashmap (silly, but will work) or you can walk up the logical tree and get the TreeViewItem's parent that happens to be an ItemsControl. The ItemsSource property will be your collection.
Get the ICollectionView for that collection.
Need to cast that ICollectionView into a CollectionView (ICollectionView doesn't implement CurrentItem setter)
Call SetCurrent(.. , ..) on the CollectionView instance
Now, anything that is bound to that ICollectionView's CurrentItem will be updated.
This became longer than I expected. Let me know if any further clarification is necesary.
My solution to this turned out to be pretty tiny.. don't know if it is equivalent to IsSynchronizedWithCurrentItem. ListView refreshes as expected.
// the XAML
<TreeView DockPanel.Dock="Left" x:Name="tvwNodes" ItemsSource="{Binding}" SelectedItemChanged="OnNewNodeSelected"/>
<ListView x:Name="lvwProperties" ItemsSource="{Binding Path=Properties}"
// the code-behind
private void OnNewNodeSelected(object sender, RoutedPropertyChangedEventArgs<object> e)
{
lvwProperties.DataContext = tvwNodes.SelectedItem; // this returns the selected Node obj
}