2012-10-31 29 views
0

我有一個WP7應用程序,到目前爲止,我已經在MVVM框架內實現了。綁定網格的列數和行數

我現在想擴展這個應用程序,這涉及到一個網格的一部分,我不知道我是否可以通過綁定來做我想做的事情。特別是

將需要可變數量的列 - 我不明白我怎麼可以用綁定來做到這一點。如果可以的話,我想根據列數來改變列的寬度。

與行相同的是一個可變數字。

我可以用這裏所需的所有信息設置虛擬機,但我看不到我可以綁定到網格以使其工作。我也想在網格中包含一些變量數據,我再也看不到如何通過綁定來實現這一點。在一個列表框中工作得很好,我剛剛綁定了對象集合,但這是完全不同的。

這是我應該只在代碼後面生成的情況嗎?我很樂意這樣做......但如果可能的話,我會很樂意嘗試並通過綁定來完成。

  • 感謝

回答

1

您可以擴展當前的電網控制,並添加一些自定義的依賴項屬性(例如列和行),並綁定到這些。這將允許您保留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 
    } 

如果你的虛擬機有屬性 '行' 和 '列',在XAML應該是這樣的:

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

太好了 - 謝謝! – Peter