私のプログラムでは、2 つのウィンドウを同時に開いています。1 つは WPF フォームで、もう 1 つは WinForms フォームです。
WinForms フォームに配置されたボタンをクリックして、WPF フォームのラベルの背景色を変更する必要があります。
どうすればいいですか?
フォーム内のコントロールが押されEventHandler
たときにイベント通知を発行するように設定できます。これは、がいつトリガーされたかを検出するために監視され、目的の設定を要求します。Button
WinForms
event
WPF
Window/UserControl
event
color
WPF
Label
MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="150" Width="225">
<Grid>
<Label Content="Label" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="100" Width="197" Background="{Binding LabelBgColour}"/>
</Grid>
</Window>
MainWindow.xaml.cs
namespace WpfApplication1
{
using System.Windows;
using System.ComponentModel;
using System.Windows.Media;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
var f = new Form1();
f.ChangedColourEventHandler += TriggeredChangedColourEventHandler;
f.Show();
}
private Brush labelBgColour;
public Brush LabelBgColour
{
get
{
return this.labelBgColour;
}
set
{
this.labelBgColour = value;
OnPropertyChanged();
}
}
private void TriggeredChangedColourEventHandler(object sender, Brush color)
{
this.LabelBgColour = color;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
Form1.cs
namespace WpfApplication1
{
using System;
using System.Windows.Forms;
using System.Windows.Media;
public partial class Form1 : Form
{
public EventHandler<Brush> ChangedColourEventHandler;
public Form1()
{
InitializeComponent();
}
private Brush bgColour;
private Brush BgColour
{
get
{
return this.bgColour;
}
set
{
this.bgColour = value;
TriggerChangedColourEventHandler(value);
}
}
private void button1_Click(object sender, EventArgs e)
{
this.BgColour = (Brush)new BrushConverter().ConvertFromString("#FF00B25A");
}
private void TriggerChangedColourEventHandler(Brush color)
{
var handler = ChangedColourEventHandler;
if (handler != null)
{
handler(this, color);
}
}
}
}
Form1
という名前の単一のButton
コントロールbutton1
があります (cs の例から判断できます)。簡潔にするために省略しForm1.Design.cs
ました。
この例では、目的の値を取得するためにWPF
ウィンドウに移動します。値がイベントの一部として送信されるように簡単に変更できます( )。WinForm
Color
Color
EventHandler
EventArgs
Winform オブジェクトが WPF フォームで使用可能で、Button1 がパブリックであると仮定すると、WPF フォームに以下のようなコードを追加する必要があります。
WinForm.Button1.Click += new System.EventHandler(Button1_Click);
private void Button1_Click(object sender, EventArgs e)
{
// Change label background
}