[英]Autosize of WPF Elementhost in WinForms not working properly
制作了一個 dummyapp 來說明我在實際應用程序中遇到的問題:
我有一個 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 應用程序中的“頂部”,如下所示:
public Form1()
{
InitializeComponent();
var elementHost = new ElementHost()
{
Dock = DockStyle.Top,
AutoSize = true
};
elementHost.Child = new WpfUserControl();
Controls.Add(elementHost);
}
啟動程序時控件顯示正確 - 但我的問題是:如果我調整窗口大小或最大化窗口,然后按下按鈕,則用戶控件根本不會更新/調整大小! ...直到我手動調整托管窗口的大小! 因此,只有在更改托管窗口的大小后,才會調整 elementhost 的大小以適應新添加的內容。
曾嘗試使用一些事件來強制托管表單在 UserControl 上執行 Update() / UpdateLayout() 等等,但沒有成功。 在不同的系統上嘗試過這個,我總是得到相同的結果。 很郁悶...
使用 DockStyle.Fill 而不是 Top。
將父窗體 (System.Windows.Forms.Form) 的AutoScroll屬性設置為true 。 它會起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.