【发布时间】:2012-07-06 07:17:34
【问题描述】:
我正在 WPF 中构建一个自定义 UserControl,它具有关联的 ViewModel。我也想在后面的代码中动态地制作控件。但是现在我在将生成的控件与 ViewModel 属性绑定时遇到了问题。我的代码是:
<UserControl x:Class="SVT.Teste.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
DataContext="UserControl1ViewModel">
<Grid Name="GridContainer">
</Grid>
</UserControl>
和后面的代码:
public UserControl1()
{
InitializeComponent();
System.Windows.Controls.Button newBtn = new Button();
newBtn.SetBinding(Button.ContentProperty, new Binding("Test"));
GridContainer.Children.Add(newBtn);
}
public class UserControl1ViewModel
{
private string test = "ola";
public string Test
{
get { return test; }
}
}
当我运行它时,我得到:
“System.Windows.Data 错误:40:BindingExpression 路径错误:'Test' 在 'object' ''String' (HashCode=-946585093)' 上找不到属性。 绑定表达式:路径=测试; DataItem='String' (HashCode=-946585093); 目标元素是 'Button' (Name='');目标属性是“内容” (类型'对象')"
你能帮帮我吗?
【问题讨论】:
标签: wpf dynamic controls code-behind