Made an dummyapp to illustrate a problem I have with a real world application:
I have a WPF User Control with content like this:
<UserControl.DataContext>
<local:ViewModel/>
</UserControl.DataContext>
<StackPanel>
<Button Content="Add to collection!" Command="{Binding AddCommand}"/>
<ItemsControl ItemsSource="{Binding Path=Collection}"/>
</StackPanel>
Datacontext is a ViewModel like this:
public class ViewModel : INotifyPropertyChanged
{
public ObservableCollection<string> Collection { get; set; }
public ICommand AddCommand { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public ViewModel()
{
Collection = new ObservableCollection<string>
{
"string number 1",
"string number 2"
};
int counter = 3;
AddCommand = new RelayCommand(x =>
{
Collection.Add($"Added string number {counter}");
counter++;
});
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
RelayCommand implements ICommand. When the add button is clicked the "AddCommand" runs, and an item is added to the collection, bound to the xaml ItemsControl. I've put the UserControl in a autosized ElementHost, docked to "Top" in my Forms app like this:
public Form1()
{
InitializeComponent();
var elementHost = new ElementHost()
{
Dock = DockStyle.Top,
AutoSize = true
};
elementHost.Child = new WpfUserControl();
Controls.Add(elementHost);
}
The control is displayed correctly when I start the program - but my problem is this: If I resize or maximize the window and then press the button, the User Control will not get updated/resized at all! ...until I manually resize the size of the hosting window! So, only after changing the size of the hosting window the elementhost will be resized to fit the newly added content.
Have tried to use some events to force the hosting form to Update() / UpdateLayout() on UserControl and so on with no success. Have tried this on different systems, and I always get the same result. Very frustrating...