WPF Binding dynamic control in code behind to ViewModel

code-behindcontrolsdynamicwpf

I'm building a custom UserControl in WPF, which has a ViewModel associated. I also want do dynamically make controls in the code behind. But now I'm having problems binding the generated controls with the ViewModel properties. My code is:

<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>

and code behind:

    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; }
        }
    }

When I run this I get:

"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')"

Can you help me?

Best Answer

You are setting DataContext property of UserControl1 to a string instead of your view model instance.

You need to do something like this:

<UserControl xmlns:local="clr-namespace:NAMESPACE_WHERE_VIEWMODEL_IS_DEFINED">
    <UserControl.DataContext>
        <local:UserControl1ViewModel />
    </UserControl.DataContext>
    <!-- unrelated code omitted -->
</UserControl>
Related Topic