我想以编程方式在一行中插入用户控件。 这是我的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);
为什么以及如何做?非常感谢。
答案 0 :(得分:0)
您忘记在第二个构造函数中调用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
之外的任何其他值,就不一定要调用这些方法。