M.Azad
M.Azad

Reputation: 3763

How to bind a property from my usercontrol content control to a property in my viewmodel?

I have a usercontrol like this:

<UserControl x:Class="MySample.customtextbox"
         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="20" d:DesignWidth="300">
    <Grid>
           <TextBox x:Name="Ytextbox"  Background="Yellow"/> 
    </Grid>
</UserControl>

I want use this control in a View such as MainWindowView How can I Binde my Ytextbox Text Property to a property in my MainWindowViewModel?

<CT:customtextbox  Text="{binding  mypropertyinviewmodel}"/>

I know that I must define a DependencyProperty for my control until I can bind a property in my viewmodel to it so i define a dependency property for my control like this:

public static readonly DependencyProperty InfoTextProperty = 
        DependencyProperty.Register("InfoText", typeof(string), typeof(customtextbox), new FrameworkPropertyMetadata(false));

public string InfoText
{
    get { return (string)GetValue(InfoTextProperty);}
    set
    {
        SetValue(InfoTextProperty, value); 
    }
} 

When I define a dependency property for my control I have a xaml error:

Error 1 Cannot create an instance of "customtextbox".

Upvotes: 0

Views: 496

Answers (3)

Sergei B.
Sergei B.

Reputation: 3227

You're trying to set boolean value to a string DependencyProperty. Should be something like that

 new FrameworkPropertyMetadata(string.Empty)

or

new FrameworkPropertyMetadata(null)

Upvotes: 1

brunnerh
brunnerh

Reputation: 185445

new FrameworkPropertyMetadata(false)

You cannot set the default value of a string property to false (which of course is a bool).

There may be some other problems (e.g. you have no binding on the TextBox in the user coontrol declaration and you try to set a property you did not register where you create an instance) but for those you should search SO.

Upvotes: 2

Saad Imran.
Saad Imran.

Reputation: 4530

Umm try this as the code for your dependency property.

public static readonly DependencyProperty InfoTextProperty = 
    DependencyProperty.Register(
        "InfoText",
        typeof(string),
        typeof(customtextbox)
    );

    public string InfoText
    {

        get { return (string)GetValue(InfoTextProperty);}
        set {SetValue(InfoTextProperty, value); }
    } 

I just removed the last parameter from when you register the property, I think that's supposed to provide a default value for the property and you were providing a boolean instead of a string, it's an optional parameter anyways.

Upvotes: 0

Related Questions