绑定网格的行数

问题描述 投票:0回答:1

我有一个WP7应用程序,到目前为止,我已经在MVVM框架内实现了。

我现在要扩展此应用程序,其中一部分涉及网格,我不确定是否可以通过绑定来完成我想做的事情。具体来说

将需要可变数量的列-我看不到如何通过绑定来做到这一点。如果可以的话,我想根据列数改变列的宽度

与行相同,涉及可变数字。

我可以使用此处所需的所有信息来设置虚拟机,但是我看不到可以绑定到网格以使其正常工作。我也想在网格中包含一些可变数据,我再也看不到如何通过绑定做到这一点。在我刚刚绑定到对象集合的列表框上工作良好,但这是完全不同的。

这是我应该在后面的代码中生成的情况吗?我很乐意这样做...但是如果可能的话,很乐意尝试通过绑定来完成它。

  • 谢谢
silverlight windows-phone-7 mvvm binding grid
1个回答
1
投票

您可以扩展当前的Grid控件并添加一些自定义的依赖项属性(例如,列和行)并绑定到这些。这将允许您保留MVVM模式。

E.G。

public class MyGridControl : Grid
{
    public static readonly DependencyProperty RowsProperty =
        DependencyProperty.Register("Rows", typeof(int), typeof(MyGridControl), new PropertyMetadata(RowsChanged));

    public static readonly DependencyProperty ColumnsProperty =
        DependencyProperty.Register("Columns", typeof(int), typeof(MyGridControl), new PropertyMetadata(ColumnsChanged));

    public static void RowsChanged(object sender, DependencyPropertyChangedEventArgs args)
    {
        ((MyGridControl)sender).RowsChanged();
    }

    public static void ColumnsChanged(object sender, DependencyPropertyChangedEventArgs args)
    {
        ((MyGridControl)sender).ColumnsChanged();
    }

    public int Rows
    {
        get { return (int)GetValue(RowsProperty); }
        set { SetValue(RowsProperty, value); }
    }

    public int Columns
    {
        get { return (int)GetValue(ColumnsProperty); }
        set { SetValue(ColumnsProperty, value); }
    }

    public void RowsChanged()
    {
        //Do stuff with this.Rows
        //E.G. Set the Row Definitions and heights
    }

    public void ColumnsChanged()
    {
        //Do stuff with this.Columns
        //E.G. Set the Column definitions and widths
    }
}

如果您的VM具有属性'Rows'和'Columns',则XAML如下所示:

<local:MyGridControl
  Rows="{Binding Rows}"
  Columns="{Binding Columns}">
</local:MyGridControl>
© www.soinside.com 2019 - 2024. All rights reserved.