gpt4 book ai didi

c# - WPF 控件初始化时未更新属性

转载 作者:行者123 更新时间:2023-11-30 18:04:25 25 4
gpt4 key购买 nike

我是 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( ... );
// ...
}
}
}

最佳答案

您已设置此绑定(bind):

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

</UniformGrid>
</UserControl>

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

您想将 UniformGrid 中的 Rows 数绑定(bind)到 BoardView.BoardRows 属性。由于 UserControl 是前面的代码片段 BoardView,您可以给 BoardView 一个名称并使用ElementName 引用它的语法如下:

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

</UniformGrid>
</UserControl>

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

关于c# - WPF 控件初始化时未更新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6165645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com