我在WPF中建立了一個自定義的UserControl,它具有一個ViewModel關聯。我也想動態地在代碼背後進行控制。但現在我遇到了將生成的控件與ViewModel屬性綁定的問題。我的代碼是:WPF在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 Error: 40 : BindingExpression path error: 'Test' property not found on 'object' ''String' (HashCode=-946585093)'. BindingExpression:Path=Test; DataItem='String' (HashCode=-946585093); target element is 'Button' (Name=''); target property is 'Content' (type 'Object')"
你能幫助我嗎?
儘管所有的答案都有效,但這對我來說是正確的答案,因爲我有一個View第一種方法,我不喜歡在後面的代碼中設置數據綁定。非常感謝你! – Louro 2012-07-06 07:45:05