我创建了一个UserControl,其中所有操作都在UserControl.xaml.cs中完成,我希望将UserControl中的特定属性(称为“值”)传递给在MainPage中创建的TextBlock。 为了测试对属性的访问,我已经在UserControl中创建了一个TextBlock,并 ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
在我的Windows Store应用程序中,我有一个带有“添加”按钮的MainPage和一个UserControl,其中包含一个TextBlock和一个Rectangle。 当我单击MainPage上的“添加”按钮时,我想创建一个新的UserControl实例并将一个字符串值分配给TextBlock。 最后,我想将UserControl实例添加到MainPage上的容器元素。
这是我的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();
}
}
这就是我在MainPage 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值,而不是尝试从代码隐藏中设置它吗?
你可以...
还考虑:为什么要在代码中创建用户控件? 您可以只将一个操作(作为字符串)添加到列表中,并使用DataTemplate将其显示在ListBox(或其他ItemsControl)中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.