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

时间:2011-03-22 12:54:48

标签: wpf c#-3.0

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

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);
            }
        }
    }

下的窗口调用此用户控件
<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),因此没有创建任何内容。

我犯了什么错误?请帮忙。

2 个答案:

答案 0 :(得分:0)

SetColumns是一个属性,您在构造函数中读取它的值,但所有属性都设置为 AFTER 构造函数调用。因此,外部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();
    }
}

答案 1 :(得分:0)

嗨,我找到了答案。它不应该在用户控件的构造函数中完成,而应该在网格加载的事件

中完成
相关问题