设置值以在网格中添加用户控件不起作用

Setvalue to add usercontrol in a grid not work

我想以编程方式在一行中插入一个用户控件。 这是我的用户控件:

public sealed partial class ItemWeek : UserControl
{
    public string nome {get;set;}
    private string luogo { get; set; }
    public DateTime dataInizio { get; set; }
    public DateTime dataFine { get; set; }

    public ItemWeek()
    {
        this.InitializeComponent();
    }
    public ItemWeek(string nome, string luogo, DateTime dataInizio, DateTime dataFine)
    {
        this.nome = nome;
        this.luogo = luogo;
        this.dataInizio = dataInizio;
        this.dataFine = dataFine;
    }

}


<Grid>
    <Grid Height="60" Width="80">
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Text="{x:Bind nome}" FontSize="23" VerticalAlignment="Center" HorizontalAlignment="Center"/>
        <TextBlock Grid.Row="1" Text="{x:Bind luogo}" FontSize="16" VerticalAlignment="Center" HorizontalAlignment="Center"/>
    </Grid>
</Grid>

我想做的只是将控件放在网格的一行中,setvalue 方法对用户控件不起作用。

  grid1.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

        ItemWeek ite = new ItemWeek("string", "string", dat, dat1);
        ite.SetValue(Grid.RowProperty, 0);
        ite.SetValue(Grid.ColumnProperty, 0);
        grid1.Children.Add(ite);

但如果我尝试插入文本块,则可以:

        TextBlock txt = new TextBlock();
        txt.Text = "teeeext";

        txt.SetValue(Grid.RowProperty, 0);
        txt.SetValue(Grid.ColumnProperty, 0);
        grid1.Children.Add(txt);

为什么以及我该怎么做?非常感谢。

您忘记在第二个构造函数中调用 InitializeComponent()

要么直接这样调用:

public ItemWeek(string nome, string luogo, DateTime dataInizio, DateTime dataFine)
{
    InitializeComponent();
    this.nome = nome;
    this.luogo = luogo;
    this.dataInizio = dataInizio;
    this.dataFine = dataFine;
}

或者像这样调用无参数构造函数:

public ItemWeek(string nome, string luogo, DateTime dataInizio, DateTime dataFine)
   : this()
{
    this.nome = nome;
    this.luogo = luogo;
    this.dataInizio = dataInizio;
    this.dataFine = dataFine;
}

可能根本不需要第二个构造函数,因为您也可以像这样使用对象初始值设定项:

var ite = new ItemWeek
{
    nome = "string",
    luogo = "string",
    dataInizio = dat,
    dataFine = dat1
};

您还应该使用静态方法 Grid.SetColumn()Grid.SetRow() 而不是 SetValue():

Grid.SetRow(ite, 0);
Grid.SetColumn(ite, 0);

调用这些方法并不是绝对必要的,只要您不设置默认值以外的任何其他值 0