Wpf 无法将值设置为用户控件属性

Wpf 无法将值设置为用户控件属性,wpf,c#-3.0,Wpf,C# 3.0,我有一个用户控件,我在其中公开了一个公共属性。基于属性值集,我尝试在运行时创建标签 public partial class MyUserControl : UserControl { public int SetColumns { get; set; } public MyUserControl() { InitializeComponent(); myGrid.Children.Cle

我有一个用户控件,我在其中公开了一个公共属性。基于属性值集,我尝试在运行时创建标签

public partial class MyUserControl : UserControl
    {
        public int SetColumns { get; set; }

        public MyUserControl()
        {
            InitializeComponent();

            myGrid.Children.Clear();
            myGrid.RowDefinitions.Add(new RowDefinition());

            for (int i = 0; i < SetColumns; i++)
            {
                //Add column.         
                myGrid.ColumnDefinitions.Add(new ColumnDefinition());
            }

            for (int j = 0; j < SetColumns; j++)     
            {                           
                Label newLabel = new Label();
                newLabel.Content = "Label" + j.ToString();
                newLabel.FontWeight = FontWeights.Bold;
                newLabel.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                Grid.SetRow(newLabel, 0);
                Grid.SetColumn(newLabel, j);
                myGrid.Children.Add(newLabel);
            }
        }
    }
公共部分类MyUserControl:UserControl
{
公共int SetColumns{get;set;}
公共MyUserControl()
{
初始化组件();
myGrid.Children.Clear();
添加(新的RowDefinition());
对于(int i=0;i
正在从窗口调用此用户控件,如下所示

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local ="clr-namespace:WpfApplication2"
        Title="MainWindow" Width="300" Height="300">
    <Grid >
        <local:MyUserControl SetColumns="10"></local:MyUserControl>
    </Grid>
</Window>

问题是,在用户控件属性中,值始终为零(0),因此不会创建任何内容


我犯了什么错误?请提供帮助。

SetColumns
是一个属性,您正在构造函数中读取它的值,但所有属性都是在构造函数调用后设置的。因此,XAML解析器执行如下操作:

var userControl = new MyUserControl(); // here you're trying to read `SetColumns`
userControl.SetColumns = 10; // here they are actually set
尝试在
SetColumns
属性设置器中更新控件:

private int _setColumns;
public int SetColumns 
{
    get { return { _setColumns; } }
    set
    {
        _setColumns = value;
        UpdateControl();
    }
}

嗨,我找到答案了。不应在用户控件的构造函数中执行此操作,而应在网格加载事件中执行此操作

似乎您正试图在用户控件的构造函数中使用SetColumns值。