【问题标题】:Trying to bind the height/width of a grid to a ViewModel尝试将网格的高度/宽度绑定到 ViewModel
【发布时间】:2012-04-21 21:55:33
【问题描述】:

所以我在视图框中有一个网格。现在网格与视图框一起缩放。但是,我需要知道 ViewModel 中网格的高度和宽度。但是它似乎没有将高度设置为任何东西?

<Viewbox VerticalAlignment="Top" Margin="5,20,5,0">
            <Border BorderThickness="6" BorderBrush="Black" CornerRadius="2">

                <Grid MinHeight="300" MinWidth="400" Height="{Binding Height, Mode=TwoWay}" Width="{Binding Width, Mode=TwoWay}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="0" >
                    <ItemsControl ItemsSource="{Binding Viewers}">
                        <ItemsControl.ItemsPanel>
                            <ItemsPanelTemplate>
                                <Canvas />
                            </ItemsPanelTemplate>
                             </ItemsControl.ItemsPanel>
                             <ItemsControl.ItemContainerStyle>
                            <Style>
                                <Setter Property="Canvas.Left" Value="{Binding X}" />
                                <Setter Property="Canvas.Top" Value="{Binding Y}"/>
                            </Style>
                        </ItemsControl.ItemContainerStyle>
                    </ItemsControl>
                </Grid>
            </Border>
        </Viewbox>

在我的 ViewModel 中:

    private int _height;
    public int Height
    {
        get
        {
            return _height;
        }

        set
        {
            _height = value;
            OnPropertyChanged("Height");
        }
    }

    private int _width;
    public int Width
    {
        get
        {
            return _width;
        }

        set
        {
            _width = value;
            OnPropertyChanged("Width");
        }
    }

有什么想法吗?

【问题讨论】:

  • 你有权利DataContext
  • 同一个 View/ViewModel 的任何其他 DataBindings 都没有问题,所以我假设是这样。
  • 我希望你在更改值时不要保持纵横比,因为那只会在边框的角半径中可见。
  • 不确定你的意思,这里真正的问题是 Height 和 Width 始终为 0 并且永远不会触发 OnPropertyChanged 事件。
  • Width 和 Height 与 ActualWidth 和 ActualHeight 不同...

标签: c# wpf xaml data-binding


【解决方案1】:

您需要在ActualWidth/Height 上绑定OneWayToSource,因为这些属性是只读的,到目前为止,我已经看到任何好的解决方案,因为如果设置在只读依赖属性上,WPF 会直接拒绝绑定。

【讨论】:

    猜你喜欢
    • 2020-05-14
    • 2017-02-21
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多