制作一个虚拟应用程序来说明我在实际应用程序中遇到的问题:
我有一个WPF用户控件,其内容如下:
<UserControl.DataContext>
<local:ViewModel/>
</UserControl.DataContext>
<StackPanel>
<Button Content="Add to collection!" Command="{Binding AddCommand}"/>
<ItemsControl ItemsSource="{Binding Path=Collection}"/>
</StackPanel>
Datacontext是一个像这样的ViewModel:
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实现ICommand。单击添加按钮时,将运行“AddCommand”,并将一个项目添加到集合中,绑定到xaml ItemsControl。我把UserControl放在一个自动化的ElementHost中,在我的Forms应用程序中停靠到“Top”,如下所示:
public Form1()
{
InitializeComponent();
var elementHost = new ElementHost()
{
Dock = DockStyle.Top,
AutoSize = true
};
elementHost.Child = new WpfUserControl();
Controls.Add(elementHost);
}
启动程序时控件显示正确 - 但我的问题是:如果我调整窗口大小或最大化然后按下按钮,用户控件根本不会更新/调整大小! ...直到我手动调整托管窗口的大小!因此,只有在更改主机窗口的大小后,才会调整elementhost的大小以适应新添加的内容。
尝试使用某些事件强制托管表单在UserControl上更新()/ UpdateLayout()等等,但没有成功。在不同的系统上试过这个,我总能得到相同的结果。非常令人沮丧......
答案 0 :(得分:0)
使用DockStyle.Fill而不是Top。
答案 1 :(得分:0)
将父表单 (System.Windows.Forms.Form) 的 AutoScroll 属性设置为 true。它会起作用。