我有一个WP7应用程序,到目前为止,我已在MVVM框架中实现。
我现在想要扩展这个应用程序,其中一部分涉及一个网格,我不确定我是否可以通过绑定做我想做的事情。具体来说
需要一个可变数量的列 - 我不知道如何通过绑定来实现这一点。如果我可以,那么我想根据列数改变列的宽度
与涉及变量编号的行相同。
我可以使用此处所需的所有信息设置VM,但我看不到我可以绑定到Grid以使其工作。我还想在网格中包含一些可变数据,我再也看不到如何通过绑定来实现这一点。与我刚刚绑定到对象集合的列表框一起工作得很好,但这是完全不同的。
这是我应该在后面的代码中生成的情况吗?我很乐意这样做......但如果可能的话,我很乐意通过绑定来尝试。
答案 0 :(得分:1)
您可以扩展当前的Grid控件并添加一些自定义依赖项属性(E.G. Columns和Rows)并绑定到这些属性。这将允许您保留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具有“行”和“列”属性,则XAML将如下所示:
<local:MyGridControl
Rows="{Binding Rows}"
Columns="{Binding Columns}">
</local:MyGridControl>