I have a WPF project where I want to launch multiple programs and embed them into my application. I have a class that inherits from HwndHost and implements the BuildWindowCore abstract method. I also registered a dependency property called FileName, and I hope to dynamically specify the program to launch through binding. Here is the code for the ListBox:
<ListBox ItemsSource="{Binding Datas}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border>
<local:PowerHwndHost FileName="{Binding Path}"/>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And here is the code for the class that inherits from HwndHost:
public class PowerHwndHost : HwndHost
{
public string FileName
{
get { return (string)GetValue(FileNameProperty); }
set { SetValue(FileNameProperty, value); }
}
public static readonly DependencyProperty FileNameProperty =
DependencyProperty.Register("FileName", typeof(string), typeof(PowerHwndHost), new PropertyMetadata(""));
protected override HandleRef BuildWindowCore(HandleRef hwndParent)
{
//dosomething
}
protected override void DestroyWindowCore(HandleRef hwnd)
{
//dosomething
}
}
And here is the code for the view model:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
}
public class MainViewModel
{
public ObservableCollection<Data> Datas { get; set; }
public MainViewModel()
{
Datas = new()
{
new Data(){Path="D:/example.exe"},
new Data(){Path="D:/example2.exe"}
};
}
}
public class Data
{
public string Path { get; set; } = "";
}
I tried to dynamically specify the program to launch through binding. I expected that when the BuildWindowCore method was called, the FileName property would have already been bound to the correct value. However, in reality, when the BuildWindowCore method was called, the binding had not even taken effect yet. I could not get the value of the FileName binding, which caused BuildWindowCore to not work properly.