【问题标题】:Bind to property of a control in another view绑定到另一个视图中控件的属性
【发布时间】:2017-07-04 08:56:26
【问题描述】:

我已经使用停靠面板和对齐方式在视图中设置了控件的高度。 我想将此控件的计算大小用作另一个视图中另一个控件的输入。

主窗口

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

查看1

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

View2(我想将按钮的高度绑定到第一个视图)

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

但它不起作用......

如果可能的话,我正在寻找具有绑定功能的仅限 xaml 的解决方案...

【问题讨论】:

  • 请您提供更多代码,您确定本地的 AncestorType 是 AnpotherView 或 AnotherView。是错字吗?或者它实际上存在于代码中。
  • “另一个视图”是指另一个窗口?它与当前窗口有什么关系,它们是同时显示的,还是这是一个模态窗口,...?
  • Gief 显式类型AncestorType={x:Type local:AnpotherView} ༼ つ ◕_◕ ༽つ
  • 已将 AnotherView 替换为 AnotherViewOfMine ...
  • 请发布您的完整标记,包括创建 Control 和 AnotherViewOfMine 的视图。除非 AnotherViewOfMine 实际上是控件的视觉祖先,否则不能使用 RelativeSource 绑定。

标签: wpf xaml binding


【解决方案1】:

您可能想尝试使用依赖属性来实现这一点。以下是基于您的案例的示例:

视图1:

<DockPanel>
        <Button x:Name="myButton" Content="Button in view1" FontSize="32"/>
    </DockPanel>

View1 代码隐藏。请注意,我们处理加载事件是为了获取按钮的实际高度并将其值分配给我们创建的 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;
        }

然后在 view2 中,我们将按钮高度绑定到该用户控件中的另一个依赖属性:

在 view2 代码隐藏中:

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();
}

最后 mainWindow xaml 看起来像这样:

<StackPanel>
    <local:View1 x:Name="View1"/>
    <local:View2 ButtonHeight="{Binding ElementName=View1,Path=ButtonHeight}"/>
</StackPanel>

还有输出:

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    相关资源
    最近更新 更多