您可能想嘗試使用依賴項屬性,以實現此目的。這是根據你的情況的例子:
視圖1:
<DockPanel>
<Button x:Name="myButton" Content="Button in view1" FontSize="32"/>
</DockPanel>
視圖1代碼隱藏。我們爲了處理加載事件的通知,以獲得按鈕的實際高度和它的值分配給我們創造了的DependencyProperty:
public static readonly DependencyProperty ButtonHeightProperty = DependencyProperty.Register(
"ButtonHeight", typeof (double), typeof (View1), new PropertyMetadata(default(double)));
public double ButtonHeight
{
get { return (double) GetValue(ButtonHeightProperty); }
set { SetValue(ButtonHeightProperty, value); }
}
public View1()
{
InitializeComponent();
}
private void View1_OnLoaded(object sender, RoutedEventArgs e)
{
ButtonHeight = myButton.ActualHeight;
}
然後在視圖2,我們的按鈕高度綁定到另一個依賴屬性在用戶控件:
並在視圖2隱藏代碼:
public static readonly DependencyProperty ButtonHeightProperty = DependencyProperty.Register(
"ButtonHeight", typeof (double), typeof (View2), new PropertyMetadata(default(double)));
public double ButtonHeight
{
get { return (double) GetValue(ButtonHeightProperty); }
set { SetValue(ButtonHeightProperty, value); }
}
public View2()
{
InitializeComponent();
}
最後在主窗口的XAML看起來是這樣的:
<StackPanel>
<local:View1 x:Name="View1"/>
<local:View2 ButtonHeight="{Binding ElementName=View1,Path=ButtonHeight}"/>
</StackPanel>
和輸出:
希望這有助於
請你提供更多的代碼,並確定了AncestorType地方是AnpotherView或AnotherView。這是一個錯字嗎?或者它實際存在於代碼中。 – lukai
有了「另一種觀點」,你的意思是另一個窗口?它與當前窗口有什麼關係,它們是同時顯示,還是這是一個模態窗口,...? – andreask
Gief explit type'AncestorType = {x:Type local:AnpotherView}'(つ◕_◕)つ – Peter