2
votes

I'm trying to figure out the correct way to bind a ViewModel to a ContentControl (I've looked all over the net but can't find an example that I can get to work correctly).

My Model:

public class Model
{

    private string _Variable = "TEST";
    public string Variable
    {
        get { return _Variable; }
        set { _Variable = value; }
    }
}

My ViewModel

public class ViewModel :ViewModelBase
{
    private Model _Model = new Model();

    public string Variable
    {
        get { return _Model.Variable; }
        set
        {
            if (_Model.Variable != value)
            {
                _Model.Variable = value;
                RaisePropertyChanged("Variable");
            }
        }
    }

My View/Window

<Window.DataContext>
    <local:ViewModel />
</Window.DataContext>

<Window.Resources>
    <DataTemplate DataType="{x:Type System:String}">
        <TextBox/>
    </DataTemplate>
</Window.Resources>

<StackPanel>
    <ContentControl Content="{Binding Path=Variable}" />
</StackPanel>

So in essence, I have (or at least I believe I have) set the content of the ContentControl to the ViewModel property 'Variable', it is of type string so the only DataTemplate should be implemented and a Textbox displayed.

And that happens... A Textbox is displayed! However the Textbox is empty, and any changes made do not impact Variable.

This means I have made an error in the Batabinding, but I don't understand where. I have a feeling that just because my DataTemplate is displaying a Textbox, nothing is actually binding the string to it, but that is the bit I'm lost over.

Thanks for any help/advice.

2
I was distracted last night and misunderstood your question. I apologize for wasting your time. I've deleted my answer. You don't need or want a DataTemplate at all for this case. Alok's answer is correct, unless your intent is something relatively unusual. If you wanted to display a string, you'd put it in a TextBlock or Label, but you still wouldn't define a DataTemplate that applies to any String in this XAML file -- strings are everywhere in a UI!15ee8f99-57ff-4f92-890c-b56153

2 Answers

1
votes

You haven't specified the TextBox's Text binding, which is completely separate to the DataContext. Since you want the TextBox to bind to its own DataContext just do this:

<TextBox Text="{Binding Path=.}"/>
0
votes

use textbox as below:

<TextBox Text="{Binding}" />