我正在 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 路径错误:在 'object' ''String' (HashCode=-946585093) 上找不到 'Test' 属性。BindingExpression:Path=Test; DataItem='String' (HashCode= -946585093); 目标元素是'Button' (Name=''); 目标属性是'Content' (类型'Object')"
你能帮助我吗?