更改父元素的子元素后,命令不起作用

时间:2016-06-09 08:42:42

标签: c# wpf children windowsformshost

我必须使用WindowsFormsHost元素来解决overlay WebBrowser问题! 但是在我追踪Children属性后,所有命令绑定都会丢失!你知道怎么重新绑定Command Bindings元素或者我怎么不丢失绑定?

XAML

<StackPanel x:Name="StackPanel">
    <Button x:Name="CloseBtn" Command="{Binding Close}"  Width="56" IsEnabled="True" Content="close" Height="26" />
</StackPanel>

代码

public partial class Test : Window
{
    public Test()
    {
        InitializeComponent();
        DataContext = new ViewModel() { Close = new DelegateCommand(this.Close) };

        Loaded += (sender, args) => Dispatcher.Invoke(new Action(AddContent));
    }

    private void AddContent()
    {
        this.FindName("CloseBtn");

        var btn = this.CloseBtn;
        //command will be worked if you uncomment following 2 lines
        //var cmd = btn.Command;
        //btn.Command = cmd;

        StackPanel.Children.RemoveAt(0);
        var wh = new WindowsFormsHost();
        var eh = new ElementHost();

        eh.Child = btn;
        wh.Child = eh;

        StackPanel.Children.Add(wh);
    }
}

我真正的问题更复杂,我必须找到并解决许多绑定已经丢失。但我只需要很好的方法解决这类问题!

0 个答案:

没有答案