在我的Windows应用商店应用中,我有一个带有"添加"按钮的主页,以及一个包含文本块和矩形的用户控件。当我单击主页上的"添加"按钮时,我想创建一个新的UserControl实例并为TextBlock分配一个字符串值。最后,我想将 UserControl 实例添加到主页上的容器元素中。
这是我的 ActionUserControl 现在的样子:
<Grid x:Name="ActionGrid">
<TextBlock x:Name="ActionText" Grid.Row="0" Text="Name Goes Here" />
</Grid>
和代码隐藏
public sealed partial class ActionUserControl : UserControl
{
public string ActionName { get; set; }
public ActionUserControl()
{
this.InitializeComponent();
}
}
这就是我在主页AddButton_Click活动中所做的
private void AddButton_Click(object sender, PointerRoutedEventArgs e)
{
// ActionCount holds number of active Actions
ActionCount++;
// Create an instance of the user control, and assign name
ActionUserControl auc = new ActionUserControl();
auc.ActionName = "Action " + ActionCount;
// Add the user control to the container
this.ActionContainer.Children.Add(auc);
// Move the add button to the bottom of the container for consistency
int childrenCount = this.ActionContainer.Children.Count;
this.ActionContainer.Children.Move((uint)childrenCount - 1, (uint)childrenCount - 2);
}
我尝试在UserControl构造函数和PageLoad事件上分配ActionText.Text = ActionName,但它们都显示为null。我应该绑定 ActionText.Text 值,而不是尝试从代码隐藏设置它吗?
你可以...
- 将操作名称设置为依赖项属性并绑定到它。
- 在 ActionName 属性资源库中更改用户控件上的文本块。
还要考虑:为什么要在代码中创建用户控件?您可以将操作(作为字符串)添加到列表中,并使用 DataTemplate 将它们显示在列表框(或其他 ItemsControl)中。