这是我实现这个的方式:
我创建了一个从 WindowsFormsHost 继承的控件
public class MyWpfControl: WindowsFormsHost
{
private MyWindowsFormsControl _winControl = new MyWindowsFormsControl ();
public MyWpfControl()
{
_winControl.KeyDown += _winControl_KeyDown;
}
void _winControl_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab && e.Shift)
{
MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
}
else if (e.KeyCode == Keys.Tab)
{
MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
}
非常适合我
使用相同的方法,您还可以使您的 Windows 控件具有所需的 wpf 数据绑定:
public static readonly RoutedEvent SelectionChangedEvent = EventManager.RegisterRoutedEvent("SelectionChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyWpfControl));
public event RoutedEventHandler SelectionChanged
{
add { AddHandler(SelectionChangedEvent, value); }
remove { RemoveHandler(SelectionChangedEvent, value); }
}
void RaiseSelectionChangedEvent()
{
var newEventArgs = new RoutedEventArgs(SelectionChangedEvent);
RaiseEvent(newEventArgs);
}
private void InitDependencyProperties()
{
_winControl.EditValueChanged += (sender, e) =>
{
SetValue(SelectedValueProperty, _winControl.EditValue);
if (!_disabledSelectionChangedEvent)
{
RaiseSelectionChangedEvent();
}
};
}
public static readonly DependencyProperty SelectedValueProperty = DependencyProperty.Register("SelectedValue", typeof(string), typeof(MyWpfControl),
new PropertyMetadata("",
(d, e) =>
{
var myControl = d as MyWpfControl;
if (myControl != null && myControl._brokersCombo != null)
{
var val = myControl.GetValue(e.Property) ?? string.Empty;
myControl._winControl.EditValue = val;
}
}, null));
这是 XAML:
<u:MyWpfControl x:Name="myWpfControl" Margin="5,0,0,0" DataSource="{Binding BindingData, UpdateSourceTrigger=PropertyChanged}" SelectedValue="{Binding SelectedPropertyNameOnViewModel, Mode=TwoWay}">
</u:MyWpfControl>