0

I have a WP7 app and so far, I have implemented within an MVVM framework.

I now want to extend this app and part of this involves a grid and I am not sure if I can do what I want to do via binding. Specifically

Will need a variable number of columns - I don't see how I can do this with binding. And if I can then I want to vary the width of the columns depending upon the number of columns

Same with the rows a variable number involved.

I can set up a VM with all the information required here, but I cannot see I can bind to the Grid to make it work. I also want to include some variable data within the grid and again, I cannot see how I can do this with binding. Worked well with a listbox where I have just bound to the collection of objects, but this is quite different.

Is this a case where I should just generate in the code behind? I am happy to do that... but would happily try and do it via binding if its possible.

  • thanks
4

1 に答える 1

1

現在のグリッドコントロールを拡張し、いくつかのカスタム依存関係プロパティ(EG列と行)を追加して、これらにバインドできます。これにより、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>
于 2012-10-31T06:37:29.183 に答える