[英]How can I capture WPF events from a Winforms app
我有一個托管在 Elementhost 中的 WPF 用戶控件。 我使用 elementhost 在我的經典 Windows 窗體應用程序中包含 WPF 用戶控件。
現在,從 Windows 窗體方面,我試圖捕獲在 WPF 標簽中生成的 mouseDown 事件,但我不知道該怎么做。
有任何想法嗎?
一個案例或許能幫到你。 winform窗體調用wpf控件。
創建 WPF 自定義控件。 控件的xaml代碼如下。
<Grid> <Image Margin="10,10,10,90" x:Name="img" Stretch="Uniform" Opacity="1"> <Image.BitmapEffect> <DropShadowBitmapEffect Opacity="1" /> </Image.BitmapEffect> </Image> <TextBox Background="Transparent" Foreground="White" Height="40" FontSize="32" Margin="44,0,56,36" x:Name="txtBox1" Opacity="0.5" Text="" VerticalAlignment="Bottom" /> </Grid>
需要添加相應的函數來設置效果。 代碼如下。
public void SetSource(string fileName) { img.Source = new BitmapImage(new Uri(fileName) ); } public void SetOpacity(double opacity) { img.Opacity = opacity; } // public string GetText() { return txtBox1.Text; }
創建Winform應用程序並添加引用,否則控件無法正常工作。 參考列表如下圖所示。
重新生成解決方案。 在左側工具欄上,出現一個 WPF 控件並將其拖到窗體中。
使用winform工程中的按鈕控件調用相應的函數。
private void button1_Click(object sender, EventArgs e) { ((UserControl1)elementHost1.Child).SetSource(@"C:\Users\Admin\Pictures\Saved Pictures\9837f99502eba3d01d4fb671cab20c15.jpg"); } private void button2_Click(object sender, EventArgs e) { ((UserControl1)elementHost1.Child).SetOpacity(0.5); } private void button3_Click(object sender, EventArgs e) { string text = ((UserControl1)elementHost1.Child).GetText(); label1.Text = text; }
測試項目:左邊是傳統的Winform控件。 右邊是導入的WPF控件。 可以清楚的看到畫面的“半透明”效果。
不確定你到底想達到什么目的。 下面是一個簡單的例子。您可以根據需要編輯 UserControl 的 MouseDown 事件。 如果有問題,請將您的問題說清楚,並給我看可以重現您的問題的完整代碼示例以供分析。
用戶控件:
<Grid>
<Label x:Name="label" Content="Label" MouseDown="label_MouseDown" Background="AliceBlue" Width="300" Height="200" />
</Grid>
private void label_MouseDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("hello");
}
在WinForms工程中添加UserControl引用,重建WinForms工程后將UserControl拖放到Form1設計器上。
運行項目,點擊UserControl中的Label,結果如圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.