WPF UserControl.Loaded事件不会触发

时间:2014-02-18 15:39:59

标签: c# wpf mvvm loaded

在我的程序中,当我将鼠标悬停在(MouseEnter事件)某个UserControl(这里我使用TransportOrderLineUserControl)时,应显示TransportOrderLineDetailView。

TransportOrderLineDetailView应放在我屏幕的右下角。为此,我需要知道ActualWidth& ActualHeight表示正确的展示位置。因为这两个属性需要具有不同于0的值,所以我使用DetailView.Loaded事件执行此代码。

我对其他两个对象使用完全相同的方式。它有效,但不适用于TransportOrderLineDetailView。

生成视图的代码:

TransportOrderLineDetailView tolDetailView = new TransportOrderLineDetailView(new TransportOrderLineDetailViewModel(transportOrderLine)); 
window.DetailContent = tolView; 
tolView.Loaded += SetDetailViewOnUI;

代码隐藏视图:

public TransportOrderLineDetailView(TransportOrderLineDetailViewModel detailViewModel)
    {
        InitializeComponent();
        DataContext = detailViewModel;
    }

方法SetDetailViewOnUI:

 private void SetDetailPanelOnUI(object sender, EventArgs e)
    {
        Canvas.SetLeft(window.DetailContentPresenter,
                                   window.grid_Root.ActualWidth - window.DetailContentPresenter.ActualWidth);
        Canvas.SetTop(window.DetailContentPresenter,
                      window.grid_Root.ActualHeight - window.DetailContentPresenter.ActualHeight);
    }

效果良好的示例:

DriverDetailView driverDetailView = new DriverDetailView(new DriverDetailViewModel(driver));
window.DetailContent = driverDetailView;
driverDetailView.Loaded += SetDetailPanelOnUI;

更多信息

  • window.DetailContent:

    private UserControl detailContent;
    
    public UserControl DetailContent
    {
        get { return this.detailContent; }
        set
        {
            this.detailContent = value;
            OnPropertyChanged("DetailContent");
        }
    }
    
  • DetailContentPresenter:

     <Canvas Grid.RowSpan="2" x:Name="canvas_Popup_DetailView">
         <ContentPresenter Content="{Binding DetailContent}" x:Name="detailContentPresenter"/>
     </Canvas>
    

未触发加载事件的测试:

 public TransportOrderLineDetailView(TransportOrderLineDetailViewModel detailViewModel)
    {
        InitializeComponent();

        DataContext = detailViewModel;
        this.Loaded += test; //Test here
    }

    private void test(object sender, System.Windows.RoutedEventArgs e)
    {
// method never executed
    }

1 个答案:

答案 0 :(得分:1)

找到解决方案。 有一个错误没有抛出。

我是如何找到它在Visual Studio中进行调试的 - &gt;例外 - &gt;勾选可能的例外情况。

希望这会帮助其他人遇到同样问题。 :)