【问题标题】:Properties not updated on WPF control initializationWPF 控件初始化时未更新属性
【发布时间】:2011-05-29 10:53:23
【问题描述】:

我是 WPF 新手,无法从 MainWindow XAML 文件中获取自定义用户控件的属性值。

在这里,我想将值“8”作为行数和列数,但在我的 InitializeGrid() 方法中,从未设置属性。它们始终为“0”。我做错了什么?

任何参考也将不胜感激。


这是我的 MainWindow.xaml(相关部分):

<local:BoardView 
    BoardRows="8" 
    BoardColumns="8"
    />

这是我的 BoardView.xaml:

<UniformGrid 
        Name="uniformGrid" 
        Rows="{Binding BoardRows}"
        Columns="{Binding BoardColumns}"
        >

    </UniformGrid>
</UserControl>

这是我的 BoardView.xaml.cs:

[Description("The number of rows for the board."),
 Category("Common Properties")]
public int BoardRows
{
    get { return (int)base.GetValue(BoardRowsProperty); }
    set { base.SetValue(BoardRowsProperty, value); }
}
public static readonly DependencyProperty BoardRowsProperty =
    DependencyProperty.Register("BoardRows", typeof(int), typeof(UniformGrid));

[Description("The number of columns for the board."),
 Category("Common Properties")]
public int BoardColumns
{
    get { return (int)base.GetValue(BoardColumnsProperty); }
    set { base.SetValue(BoardColumnsProperty, value); }
}
public static readonly DependencyProperty BoardColumnsProperty =
    DependencyProperty.Register("BoardColumns", typeof(int), typeof(UniformGrid));

public BoardView()
{
    InitializeComponent();
    DataContext = this;
    InitializeGrid();
}

private void InitializeGrid()
{
    int rows = BoardRows;
    int cols = BoardColumns;

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            uniformGrid.Children.Add( ... );
            // ...
        }
    }
}

【问题讨论】:

    标签: c# wpf xaml initialization dependency-properties


    【解决方案1】:

    您已设置此绑定:

    <UserControl ...>
        <UniformGrid 
            Name="uniformGrid" 
            Rows="{Binding BoardRows}"
            Columns="{Binding BoardColumns}"
            >
    
        </UniformGrid>
    </UserControl>
    

    问题是您的绑定不起作用,因为该绑定使用默认数据源,即UserControlDataContext。您可能还没有设置DataContext,但这没关系,因为这不是您想要的。

    您希望将UniformGrid 中的Rows 的数量绑定到BoardView.BoardRows 属性。由于UserControl 是之前的代码sn -p is a BoardView,因此您可以给BoardView 一个名称,并使用ElementName 语法来引用它,如下所示:

    <UserControl Name="boardView" ...>
        <UniformGrid 
            Name="uniformGrid" 
            Rows="{Binding BoardRows, ElementName=boardView}"
            Columns="{Binding BoardColumns, ElementName=boardView}"
            >
    
        </UniformGrid>
    </UserControl>
    

    这表示:“将UniformGrid.Row 绑定到名为boardView 的元素的BoardRows 属性”,正是您想要的!

    【讨论】:

    • 谢谢,修复了属性更新。我还必须将对 InitializeGrid() 的调用移至 uniformGrid_Loaded;不能在构造函数中拥有它。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    相关资源
    最近更新 更多