2017-07-04 109 views
0

我已经在视图中设置了使用dockpanels和路线的控件的高度。 我想使用此控件的计算大小作为另一个视图中另一个控件的输入。在另一个视图中绑定到控件的属性

主窗口

<StackPanel> 
    <local:View1 /> 
    <local:View2 /> 
</StackPanel> 

视图1

<DockPanel> 
    ... 
     <Button x:Name="myButton" /> 
    ... 
</DockPanel> 

视图2(在这里我想按钮的高度绑定到第一视图)

<Button Height="{Binding Path=Button.Height, RelativeSource={RelativeSource AncestorType={x:Type local:View1}}}" /> 

但它不工作...

I我正在寻找如果可能xaml唯一的解决方案与绑定...

+0

请你提供更多的代码,并确定了AncestorType地方是AnpotherView或AnotherView。这是一个错字吗?或者它实际存在于代码中。 – lukai

+0

有了“另一种观点”,你的意思是另一个窗口?它与当前窗口有什么关系,它们是同时显示,还是这是一个模态窗口,...? – andreask

+0

Gief explit type'AncestorType = {x:Type local:AnpotherView}'(つ◕_◕)つ – Peter

回答

0

您可能想尝试使用依赖项属性,以实现此目的。这是根据你的情况的例子:

视图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> 

和输出:

enter image description here

希望这有助于

相关问题