ViewModel が関連付けられている WPF でカスタム UserControl を構築しています。また、コード ビハインドでコントロールを動的に作成したいと考えています。しかし、生成されたコントロールを 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)'.BindingExpression:Path=Test; DataItem='String' (HashCode= -946585093); ターゲット要素は 'ボタン' (Name=''); ターゲット プロパティは 'コンテンツ' (タイプ 'オブジェクト')"
手伝って頂けますか?