添加新子项后,JavaFX会将子项的属性绑定到其父项的属性

时间:2015-10-08 12:24:21

标签: java javafx-8

我有一个可缩放的Pane。我想分别在这个Pane中扩展所有孩子。可以动态添加子项,因此我想在添加新子项后将子项的scale属性绑定到其父项的scale属性但我不知道如何执行此操作。

我在缩放窗格时立即缩放所有子项:

public class ZoomableCanvas extends Pane {

    DoubleProperty scale = new SimpleDoubleProperty(1.0);

    public ZoomableCanvas() {
        scaleXProperty().bind(scale);
        scaleYProperty().bind(scale);
    }

    public double getScale() {
        return scale.get();
    }

    public void setScale(double scale) {
        this.scale.set(scale);
        for (javafx.scene.Node child : getChildren()) {
            child.setScaleX(scale);
            child.setScaleY(scale);
        }
    }

    public void setPivot(double x, double y) {
        setTranslateX(getTranslateX() - x);
        setTranslateY(getTranslateY() - y);
    }
}

但必须有一种更优雅的方式。我如何监听添加子项然后绑定属性?

1 个答案:

答案 0 :(得分:1)

观察儿童名单:

<views:BaseWindowView  
    x:Class="mv.Office.Presentation.Views.MessageBoxWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:views="clr-namespace:mv.Office.Presentation.Common.Views;assembly=mv.Office.Presentation.Common"
    xmlns:viewModles="clr-namespace:mv.Office.Presentation.ViewModels"
    xmlns:w="clr-namespace:System.Windows;assembly=PresentationFramework"
    xmlns:converters="clr-namespace:mv.Office.Presentation.Common.Converters;assembly=mv.Office.Presentation.Common"
    x:TypeArguments="viewModles:MessageBoxViewModel"
    mc:Ignorable="d" 
    Style="{DynamicResource MessageWindowStyle}"
    WindowStartupLocation="CenterScreen"
    SizeToContent="WidthAndHeight" MaxWidth="400" MinWidth="200"
    ResizeMode="NoResize"
    Name=MessageBox
    d:DesignHeight="300" d:DesignWidth="300">
    <Window.Resources>
        <converters:ObjectToVisibilityConverter x:Key="ObjectToVisibilityConverter"/>
        <converters:MessageBoxImageToBitmapImageConverter x:Key="MessageBoxImageToBitmapImageConverter"/>
    </Window.Resources>
</views:BaseWindowView>