Alexandre
Alexandre

Reputation: 13318

DataContext in WPF throws an exception

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox Name="myTxt" Text="{Binding}" />
    </Grid>
</Window>

namespace WpfApplication1
{

    public partial class MainWindow : Window
    {
        public MainWindow()
        {

            InitializeComponent();
            DataContext = "fdfsfds";
        }
    }
}

I wonder why this code isn't working? It throws an exception. What should I do to bind textBox?

Upvotes: 0

Views: 612

Answers (2)

stukselbax
stukselbax

Reputation: 5935

The default Binding for TextBox.Text property - is TwoWay

"Two-way binding requires Path or XPath."

So, you can use OneWay Binding:

<Grid>
    <TextBox Name="myTxt" Text="{Binding Mode=OneWay}" />
</Grid>

Upvotes: 3

scor4er
scor4er

Reputation: 1589

If you still want TwoWay binding you may use this code:

<TextBox Name="myTxt" Text="{Binding Path=DataContext, RelativeSource={RelativeSource Self}}" />

Upvotes: 1

Related Questions