简体   繁体   中英

WPF binding to contentcontrol.child called twice

I am developing a MVVM application

I want to bind to a WindowsFormHost in my application.But WindowsFormHost is not a dependancyproperty.

So in my view model create a new WindowsFormHost and bind it to a child of a contentcontrol.But i encountered that binding called twice when i run the programe.

Any suggestions??

My XAML

<Window x:Class="Demo.View.area"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Demo.View"
    mc:Ignorable="d"
    Title="area" Height="300" Width="300">
   <ContentControl Content="{Binding myWindow}" />
</Window>

my viewModel.cs contain following implementation

public WindowsFormsHost myWindow
{
    get
    {
       return new WindowsFormsHost() { Child = newWindow }; 
       //newWindow defined in another place
    }
}

The root issue here is that you create a new object every time the property getter is called. There are very few scenarios in which that would be a good idea, and it certainly isn't in your case.

We can fix the immediate problem by just not doing that. For example:

private readonly Lazy<WindowsFormsHost> _myWindow =
    new Lazy<WindowsFormsHost>(() => new WindowsFormsHost() { Child = newWindow });

public WindowsFormsHost myWindow
{
    get { return _myWindow.Value; }
}

That will defer creation of the object until the first time the property getter is called, but after that will always return the same value.

But that doesn't really solve your broader problem. There's not enough context in your question to understand why you think this code is useful, but I think it very unlikely to be the code you really want.

Your view model should not be creating view objects at all. You can and should be declaring the WindowsFormsHost and its child in the XAML, just like you would any other view component.

It also doesn't make sense to contain a WindowsFormsHost component as the child of a ContentControl . It's a perfectly valid control all by itself, and does not need a container.

This answer should address the specific issue you're asking about. But I strongly encourage you to rethink your design. It seems all wrong. If you want help with it, post a new question that includes a good [mcve] that has enough detail that shows exactly what broader goal you're actually trying to solve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM