【问题标题】:Binding the number of columns and rows of a Grid绑定Grid的列数和行数
【发布时间】:2012-10-20 12:13:06
【问题描述】:

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

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

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

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

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

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

  • 谢谢

【问题讨论】:

    标签: silverlight windows-phone-7 mvvm binding grid


    【解决方案1】:

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

    例如

    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 具有“行”和“列”属性,则 XAML 将如下所示:

    <local:MyGridControl
      Rows="{Binding Rows}"
      Columns="{Binding Columns}">
    </local:MyGridControl>
    

    【讨论】:

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