在网格中添加用户控件的Setvalue不起作用

本文关键字:Setvalue 不起作用 控件 用户 网格 添加 | 更新日期: 2023-09-27 18:17:41

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

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

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

在网格中添加用户控件的Setvalue不起作用

您忘记在第二个构造函数中调用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之外的任何其他值即可。