Event firing when ComboBox.Items count changed? - wpf

I couldn't find a proper event which fires when my ComboBox.Items count changed. Is there any way to do so?

Bind ComboBox ItemsSource to ObservableCollection, then you can catch the event CollectionChanged of ObservableCollection
EDIT:
In wpf it is recommended to use binding instead of accessing UI element properties directly, of course better to use MVVM, but you can live without it too
in your Windows or UserControls C# code you can keep property like this
public ObservableCollection<string> MyCollection{get;set;}
Initialize it in constructor
MyCollection = new ObservableCollection<string>()
MyCollection.CollectionChanged += SomeMethod;
than name your UserControl in xaml like this
<UserControl Name="myUserControl".../>
write your ComboBox like this
<ComboBox ItemsSource="{Binding ElementName=myUserControl, Path=MyCollection}"...
now instead of adding and removing items to combobox element, add tham to MyCollection, they will appear in combobox
Hope this helps

Don't think that there is any event to fire when ComboBox.Items count changed. You probably should do the code when you add or remove the items.
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
End Sub
OR
protected void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}

Related

WPF Can I use a DataTrigger to have the View do something after the View Model changes the value of a Property?

My WPF MVVM VB.NET app loads a list of songs into a ListBox at start. The list contents populate in a BackgroundWorker that is kicked off in the Constructor of the ViewModel. Once this is done, I want to set focus to the first song in the list.
As setting this focus is purely a View operation, I want it in the code-behind of the XAML. It's no business of the ViewModel where focus goes.
I tried doing this on various Window and ListBox events, but they either don't fire, or fire too early. So I'm think what I need is a Boolean Property that the ViewModel sets when it's done loading the songs into the list. That's when I need the View to catch that Property Change, and call the code-behind function that has the logic to maniuplate the View, in the is case, setting focus on the first song in the list.
But this is where my knowledge of WPF is short. I searched and it sounds like DataTrigger could do the trick. But where to put it, and what's the right syntax, and how to have it call my code-behind function?
Or is there an even simpler way that I'm overlooking. This seems like a basic functionality - to trigger some code-behind action in the View when a Property changes a certain way in the ViewModel.
Here's the code-behind function. I can elaborate it once it's successfully getting called at the intended time:
Private Sub FocusSongsList()
' set focus back to the Songs list, selected item (couldn't just set focus to the list, it ran forever and looks like it set focus to every item in turn before releasing the UI)
Dim listBoxItem = CType(LstSongs.ItemContainerGenerator.ContainerFromItem(LstSongs.SelectedItem), ListBoxItem)
If Not listBoxItem Is Nothing Then
listBoxItem.Focus()
End If
End Sub
Here's my ListBox:
<ListBox x:Name="LstSongs" ItemsSource="{Binding FilteredSongs}" DisplayMemberPath="Path"
HorizontalAlignment="Stretch"
SelectionMode="Extended" SelectionChanged="LstSongs_SelectionChanged" Loaded="FocusSongsList"/>
And I would define a new property that can be set from the RunWorkerCompleted part of the BackgroundWorker.
Private _InitialSongLoadCompleted As Boolean
Public Property InitialSongLoadCompleted() As Boolean
Get
Return _InitialSongLoadCompleted
End Get
Set(ByVal value As Boolean)
_InitialSongLoadCompleted = value
RaisePropertyChanged("InitialSongLoadCompleted")
End Set
End Property
A DataTrigger can't execute methods. It can only set properties.
Focus can't be activated by setting a property, therefore a DataTrigger can't solve your problem.
Generally, if you have longrunning initialization routines you should move them to an init routine (which could be async) or use Lazy<T>.
For example, you instantiate your view model class and call Initialize() afterwards. After the method has returned you can continue to initialize the ListBox:
MainWindow.xaml.cs
Partial Class MainWindow
Inherits Window
Private ReadOnly Property MainViewModel As MainViewModel
Public Sub New(ByVal dataContext As TestViewModel, ByVal navigator As INavigator)
InitializeComponent()
Me.MinViewModel = New MainViewMdel()
Me.DataContext = Me.MainViewModel
AddHandler Me.Loaded, AddressOf OnLoaded
End Sub
' Use the Loaded event to call async methods outside the constructor
Private Async Sub OnLoaded(ByVal sender As Object, ByVal e As EventArgs)
Await mainViewModel.InitializeAsync()
' For example handle initial focus
InitializeListBox()
End Sub
End Class
MainViewModel.cs
Class MainViewModel
Inherits INotifyPropertyChanged
Public Async Function InitializeAsync() As Task
Await Task.Run(AddressOf InitializeSongList)
End Function
Private Sub InitializeSongList()
' TODO::Initialize song list
End Sub
End Class
It has been a long long time since I wrote much VB, so I'm afraid this is c# code.
You can handle targetupdated on a binding.
This fires when data transfers from the source ( viewmodel property ) to the target (the ui property and here itemssource)
<ListBox
x:Name="LstSongs"
ItemsSource="{Binding Songs, NotifyOnTargetUpdated=True}"
TargetUpdated="ListBox_TargetUpdated"/>
When you replace your list, that targetupdated will fire.
If you raise property changed then the data will transfer ( obviously ).
private async void ListBox_TargetUpdated(object sender, DataTransferEventArgs e)
{
await Task.Delay(200);
var firstItem = (ListBoxItem)LstSongs.ItemContainerGenerator
.ContainerFromItem(LstSongs.Items[0]);
firstItem.Focus();
Keyboard.Focus(firstItem);
}
As that data transfers, there will initially be no items at all of course so we need a bit of a delay. Hence that Task.Delay which will wait 200ms and should let the UI render. You could make that a bit longer or dispatcher.invokeasync.
It finds the first container and sets focus plus keyboard focus.
It might not be at all obvious that item has focus.
A more elegant approach using dispatcher will effectively schedule this focussing until after the ui has rendered. It might, however, look rather tricky to someone unfamiliar with c#
private void ListBox_TargetUpdated(object sender, DataTransferEventArgs e)
{
Dispatcher.CurrentDispatcher.InvokeAsync(new Action(() =>
{
var firstItem = (ListBoxItem)LstSongs.ItemContainerGenerator
.ContainerFromItem(LstSongs.Items[0]);
firstItem.Focus();
Keyboard.Focus(firstItem);
}), DispatcherPriority.ContextIdle);
}
If you want a blue background then you could select the item.
firstItem.IsSelected = true;
Or you could use some datatrigger and styling working with IsFocused.
https://learn.microsoft.com/en-us/dotnet/api/system.windows.uielement.isfocused?view=windowsdesktop-7.0
( Always distracts me that, one s rather than two and IsFocussed. That'll be US english I gues )
Here's my mainwindowviewmodel
public partial class MainWindowViewModel : ObservableObject
{
[ObservableProperty]
private List<string> songs = new List<string>();
MainWindowViewModel()
{
Task.Run(() => { SetupSongs(); });
}
private async Task SetupSongs()
{
await Task.Delay(1000);
Songs = new List<string> { "AAA", "BBB", "CCC" };
}
}
I'm using the comunity toolkit mvvm for code generation. Maybe it does vb as well as c#.
You might accomplish your goal by defining a custom event in the viewmodel which is raised when the list processing is complete. The view can subscribe to it and act accordingly.
It would look something like this:
Class MyViewModel
'Custom eventargs shown for completeness, you can use EventHandler if you
'don't need any custom eventargs.
Public Event ListCompleted As EventHandler(Of ListCompletedEventArgs)
'...
Public Sub ProcessSongList()
'Note that if this runs on a background thread, you may need to
'get back on the UI thread to raise an event for the view to handle
RaiseEvent ListCompleted(Me, New ListCompletedEventArgs())
End Sub
End Class
Class MyView
Public Sub New(ByVal vm as MyViewModel)
Me.DataContext = vm
AddHandler vm.ListCompleted, AddressOf OnListCompleted
End Sub
Private Sub OnListCompleted(ByVal sender As Object, ByVal args As ListCompletedEventArgs)
'...
End Sub
'...
End Class
You mentioned doing processing on a background thread. I'm not completely sure which thread the completion event would issue into, but beware that UI stuff can only happen on the UI thread so you might need to use a Dispatcher.Invoke to make sure your code runs on the right thread. I'd do it to run the RaiseEvent so the view doesn't need to know anything about it.

Apply and validate a bound DataGridViewComboBoxCell directly upon selection change

I have a windows forms DataGridView that contains some DataGridViewComboBoxCells that are bound to a source collection using DataSource, DisplayMember and ValueMember properties. Currently the the combobox cell commits the changes (i.e. DataGridView.CellValueChanged is raised) only after I click on another cell and the combobox cell loses focus.
How would I ideally commit the change directly after a new value was selected in the combobox.
This behaviour is written into the implementation of the DataGridViewComboBoxEditingControl. Thankfully, it can be overridden. First, you must create a subclass of the aforementioned editing control, overriding the OnSelectedIndexChanged method:
protected override void OnSelectedIndexChanged(EventArgs e) {
base.OnSelectedIndexChanged(e);
EditingControlValueChanged = true;
EditingControlDataGridView.NotifyCurrentCellDirty(true);
EditingControlDataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
This will ensure that the DataGridView is properly notified of the change in item selection in the combo box when it takes place.
You then need to subclass DataGridViewComboBoxCell and override the EditType property to return the editing control subclass from above (e.g. return typeof(MyEditingControl);). This will ensure that the correct editing control is created when the cell goes into edit mode.
Finally, you can set the CellTemplate property of your DataGridViewComboBoxColumn to an instance of the cell subclass (e.g. myDataGridViewColumn.CellTemplate = new MyCell();). This will ensure that the correct type of cell is used for each row in the grid.
I tried using Bradley's suggestion, but it was sensitive to when you attached the cell template. It seemed like I couldn't allow the design view to wire up the column, I had to do it myself.
Instead, I used the binding source's PositionChanged event, and triggered updates from that. It's a little bit odd, because the control is still in edit mode, and the databound object doesn't get the selected value yet. I just updated the bound object myself.
private void bindingSource_PositionChanged(object sender, EventArgs e)
{
(MyBoundType)bindingSource.Current.MyBoundProperty =
((MyChoiceType)comboBindingSource.Current).MyChoiceProperty;
}
A better way to achieve this that I am using successfully rather than subclassing or the somewhat inelegant binding source method above, is the following (sorry it's VB but if you can't translate from VB to C# you have bigger problems :)
Private _currentCombo As ComboBox
Private Sub grdMain_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles grdMain.EditingControlShowing
If TypeOf e.Control Is ComboBox Then
_currentCombo = CType(e.Control, ComboBox)
AddHandler _currentCombo.SelectedIndexChanged, AddressOf SelectionChangedHandler
End If
End Sub
Private Sub grdMain_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdMain.CellEndEdit
If Not _currentCombo Is Nothing Then
RemoveHandler _currentCombo.SelectedIndexChanged, AddressOf SelectionChangedHandler
_currentCombo = Nothing
End If
End Sub
Private Sub SelectionChangedHandler(ByVal sender As Object, ByVal e As System.EventArgs)
Dim myCombo As ComboBox = CType(sender, ComboBox)
Dim newInd As Integer = myCombo.SelectedIndex
//do whatever you want with the new value
grdMain.NotifyCurrentCellDirty(True)
grdMain.CommitEdit(DataGridViewDataErrorContexts.Commit)
End Sub
That's it.

Handling events from user control containing a WPF textbox

In order to take advantage of the spell checking ability of WPF textboxes, I have added one to a user control (with the use of elementhost). This user control is used in various window forms. My current problem is trying to handle keyup events from this textbox but the windows form is unable to "get" any event from the control. I can access the properties of the textbox just fine (i.e. text, length, etc.) but keyboard events don't seem to work.
I have found, however, that the following will bring back events from the WPF textbox:
Public Class MyUserControl
Private _elementHost As New ElementHost
Private _wpfTextbox As New System.Windows.Controls.Textbox
Private Sub MyUserControl_Load(...) Handles Me.Load
Me.Controls.Add(_elementHost)
_elementHost.Dock = DockStyle.Fill
_elementHost.Child = _wpfTextbox
Dim MyEventInfo As EventInfo
Dim MyMethodInfo As MethodInfo
MyMethodInfo = Me.GetType().GetMethod("WPFTextbox_KeyUp")
MyEventInfo = _wpfTextBox.GetType().GetEvent("PreviewKeyUp")
Dim dlg As [Delegate] = [Delegate].CreateDelegate(MyEventInfo.EventHandlerType, Me, MyMethodInfo)
MyEventInfo.AddEventHandler(_wpfTextBox, dlg)
End Sub
Public Sub WPFTextbox_KeyUp(ByVal sender As Object, ByVal e As RoutedEventArgs)
' something goes here
End Sub
End Class
The user control is now able to do something after the PreviewKeyUp event is fired in the WPF textbox. Now, I'm not completely sure how to have the window form containing this user control to work with this.
Im a C# person not VB so please bear with me.. Basically you could assign the event from your Window rather than within your UserControl.. So in the constructor of your Window assign the PreviewKeyUp:
this.myUserContorl.PreviewKeyUp += new System.Windows.Input.KeyEventHandler(WPFTextbox_KeyUp);
then place the event handler in your Window:
private void WPFTextbox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
}
Incidentally you needn't go through the hassle of capturing the event in your UserControl as you can still access your TextBox within you UserControl directly from your Window (if you make it public), again from your constructor in your Window:
this.myUserContorl.wpfTextbox.PreviewKeyUp += new System.Windows.Input.KeyEventHandler(WPFTextbox_KeyUp);
I imagine it would look like this in VB (at a guess):
AddHandler myUserContorl.wpfTextbox.PreviewKeyUp, AddressOf WPFTextbox_KeyUp
ElementHost has a static method called EnableModelessKeyboardInterop(). Try calling it?
ElementHost.EnableModelessKeyboardInterop();
Read more here
Seems basic, but did you set the KeyPreview to TRUE on your form?

Setting User Control's DataContext from Code-Behind

This should be pretty easy, but it throws VS2008 for a serious loop.
I'm trying out WPF with MVVM, and am a total newbie at it although I've been developing for about 15 years, and have a comp. sci. degree. At the current client, I am required to use VB.Net.
I have renamed my own variables and removed some distractions in the code below, so please forgive me if it's not 100% syntactically perfect! You probably don't really need the code to understand the question, but I'm including it in case it helps.
I have a very simple MainView.xaml file:
<Window x:Class="MyApp.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Main Window" Height="400" Width="800" Name="MainWindow">
<Button Name="Button1">Show Grid</Button>
<StackPanel Name="teststack" Visibility="Hidden"/>
</Window>
I also have a UserControl called DataView that consists of a DataGrid:
<UserControl x:Class="MyApp.Views.DataView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WpfToolkit="http://schemas.microsoft.com/wpf/2008/toolkit" >
<Grid>
<WpfToolkit:DataGrid
ItemsSource="{Binding Path=Entries}" SelectionMode="Extended">
</WpfToolkit:DataGrid>
</Grid>
</UserControl>
The constructor for the DataView usercontrol sets up the DataContext by binding it to a view model, as shown here:
Partial Public Class DataView
Dim dataViewModel As ViewModels.DataViewModel
Public Sub New()
InitializeComponent()
dataViewModel = New ViewModels.DataViewModel
dataViewModel.LoadDataEntries()
DataContext = dataViewModel
End Sub
End Class
The view model for DataView looks like this (there isn't much in ViewModelBase):
Public Class DataViewModel
Inherits ViewModelBase
Public Sub New()
End Sub
Private _entries As ObservableCollection(Of DataEntryViewModel) = New ObservableCollection(Of DataEntryViewModel)
Public ReadOnly Property Entries() As ObservableCollection(Of DataEntryViewModel)
Get
Return _entries
End Get
End Property
Public Sub LoadDataEntries()
Dim dataEntryList As List(Of DataEntry) = DataEntry.LoadDataEntries()
For Each dataentry As Models.DataEntry In dataEntryList
_entries.Add(New DataEntryViewModel(dataentry))
Next
End Sub
End Class
Now, this UserControl works just fine if I instantiate it in XAML. When I run the code, the grid shows up and populates it just fine.
However, the grid takes a long time to load its data, and I want to create this user control programmatically after the button click rather than declaratively instantiating the grid in XAML. I want to instantiate the user control, and insert it as a child of the StackPanel control:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
Dim dataView As New DataView
teststack.Children.Add(dataView)
End Sub
When I do this, as soon as the Button1_Click finishes, my application locks up, starts eating RAM, and hits the CPU about 50%.
Am I not instantiating my UserControl properly? It all seems to come down to the DataContext assignment in DataEntry's constructor. If I comment that out, the app works as expected (without anything in the grid, of course).
If I move this code block into Button1_Click (basically moving DataEntry's constructor code up a level), the app still fails:
dataViewModel = New ViewModels.DataViewModel
dataViewModel.LoadDataEntries()
dataView.DataContext = dataViewModel
I'm stumped. Can anybody give me some tips on what I could be doing wrong, or even how to debug what infinite loop my app is getting itself into?
Many thanks.
The root cause of your issue appears to be either the raw amount of data you're loading or some inefficiency in how you load that data. Having said that, the reason you're seeing the application lock up is that you're locking the UI thread when loading the data.
I believe that in your first case the data loading has been off loaded onto another thread to load the data. In you second example you're instantiating the control on the UI thread and as a result all the constructor and loading logic is performed on the current thread (the UI thread). If you offload this work onto another thread then you should see similar results to the first example.
I eventually gave up on trying to get the DataContext on the UserControl set during instantiation of the UserControl (either in XAML or code). Now I load up the data and set the DataContext of the UserControl in an event in the UserControl (IsVisibleChanged, I believe). When I instantiate the UserControl in XAML, I have it's Visibility set to Hidden. When Button1 is clicked, I set the UserControl's Visibility to Visible. So the UserControl pops into view, and it loads up its data and DataContext is set. Seems to work, but also seems very kludgey. :-( Thanks for the help, folks!
If it's only a matter of your control taking a long time to populate data, you should populate the control on another thread then add it through a delegate:
Since I'm not too good at writing VB.NET, but here's the C# equivalent:
private void Button1_Click(Object sender, RoutedEventArgs e)
{
Thread thr = new Thread(delegate()
{
DataView dataView = new DataView();
this.Dispatcher.BeginInvoke((Action) delegate()
{
teststack.Children.Add(dataView);
});
});
thr.Start();
}

WPF Binding to a Combo using only a subset of a Collection's items

I'm trying to set a TwoWay binding to a combo box using only a selection of a collection's objects. Currently, everything works out ok if I just want to bind everything in the colelction, but in the example class below, what if I only want to show items where Active=True? I can filter the items using LINQ like ItemsSource = FROM x IN Coll WHERE x.Active=True but then I lose the TwoWay binding. Ie, if the name or the active state in the source is updated from elsewhere, the combo box does not automatically update.
Is the possible to do? If not, does anyone who has had to deal with this have some suggestions?
'The Class
Public Class Test
Implements ComponentModel.INotifyPropertyChanged
Private _Name As String
Private _Active As Boolean
Public Sub New(Name As String, Active As Boolean)
_Name=Name
_Active=Active
End Sub
Public Property Name() As String
End Class
'Declare a Collection and add some Tests, then bind to Cbo in Page Load
Dim Coll As New ObservableCollection
Coll.Add(New Test("Test1", True))
Coll.Add(New Test("Test2", False))
Coll.Add(New Test("Test3", True))
TheComboBox.ItemsSource=Coll
Two options:
You can use a framework like Bindable LINQ that makes your LINQ queries return observable collections (thus the binding stays as two-way).
Or you could bind your ComboBox's items to a CollectionViewSource and run each item through a Filter event handler:
<CollectionViewSource
Source="{Binding MyItems}"
Filter="OnlyActiveItems"
x:Key="ItemsView"/>
<ComboBox ItemsSource="{Binding Source={StaticResource ItemsView}}" />
with code-behind:
private void OnlyActiveItems(object sender, FilterEventArgs e)
{
e.Accepted = false;
var item = e.Item as Text;
if (item == null) return;
e.Accepted = item.Active;
}
Note that I'm not entirely sure that a CollectionViewSource will recognise the INotifyPropertyChanged interface and re-query the list when one element changes. I'd really suggest Bindable LINQ if the filter approach doesn't work.
The CollectionViewSource class can add sorting and filtering to any WPF items control

Resources