C # convert Control to UIElement

2

How can I convert a Control to UIElement in Windows forms with ?

I'm extracting Controls from FlowLayoutPanel with Controls but I want to convert them to UIElement

    
asked by Fer garcia 24.12.2015 в 01:24
source

2 answers

8

I think you're mixing with and this is not possible. (if you can use UserControls done in ), but convert a Control to UIElement is not possible.

UIElement derives from other classes

System.Object
  System.Windows.Threading.DispatcherObject
    System.Windows.DependencyObject
      System.Windows.Media.Visual
        System.Windows.UIElement

View on MSDN

While Control

System.Object
  System.MarshalByRefObject
    System.ComponentModel.Component
      System.Windows.Forms.Control

View on MSDN

I think the casting or conversion will not be possible, you should rethink because you want to convert it to UIElement in a .

    
answered by 24.12.2015 / 02:21
source
3

You can not convert a control from Windows Forms to UIElement , because they are objects that belong to very different hierarchies.

If you want to use a control of Windows Forms in WPF you should use a control WindowsFormsHost

<Window x:Class="HostingWfInWpf.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"  
    Title="HostingWfInWpf"
    >

    <Grid>
        <WindowsFormsHost>
            <wf:MaskedTextBox x:Name="mtbDate" Mask="00/00/0000"/>
        </WindowsFormsHost>

    </Grid>
</Window>

To be able to use it, do not forget to add a reference to WindowsFormsIntegration.dll

You can also do it by code

private void LoadWFUserControl() 
{
    System.Windows.Forms.Integration.WindowsFormsHost host =
        new System.Windows.Forms.Integration.WindowsFormsHost();
    MyFormscontrol uc_myControl= new MyFormscontrol ();
    host.Child = uc_myControl;
    this.grid1.Children.Add(host);
}
    
answered by 12.01.2016 в 22:37