9

I have a WPF project in which I have 4 TextBlock. What I want is to change the Text of each TextBlock via Binding.

So far I have my XAML:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock x:Name="First" Text="{Binding FirstString}" Grid.Row="0"/>
    <TextBlock x:Name="Second" Text="{Binding SecondString}" Grid.Row="1"/>
    <TextBlock x:Name="Third" Text="{Binding ThirdString}" Grid.Row="2"/>
    <TextBlock x:Name="Fourth" Text="{Binding FourthString}" Grid.Row="3"/>
</Grid>

And in my code I have:

public partial class MainWindow : Window
{
    public string FirstString { get; set; }
    public string SecondString { get; set; }
    public string ThirdString { get; set; }
    public string FourthString { get; set; }

    public MainWindow()
    {
        InitializeComponent();

        FirstString = "First";
        SecondString = "Second";
        ThirdString= "Third";
        FourthString= "Fourth";
    }
}

But the Binding doesn't work at all. Am I doing something wrong?

EDIT: After following Chris Mantle's suggestion in the comments to look at the debug output (I had to enable Warnings for the Binding), I get the following error:

System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=FirstString; DataItem=null; target element is 'TextBlock' (Name='First'); target property is 'Text' (type 'String')

4
  • 1
    Is there anything in the Output window? Aug 5, 2013 at 14:09
  • Nothing at all. And i cant find why.
    – oimitro
    Aug 5, 2013 at 14:11
  • 3
    Can you turn up your data binding information in the Output Window and see if there's any more detail? (Tools menu –> Options –> Debugging –> Output Window –> WPF Trace Settings –> Data Binding, set to something like Verbose or All) Aug 5, 2013 at 14:13
  • who is the datacontext of the window. this should be this.
    – JSJ
    Aug 5, 2013 at 14:26

5 Answers 5

22

There are a few things that are incorrect. The Binding markup will look at the object in the DataContext property of the control. This property inherits the DataContext from the declaring parent unless otherwise specified. Out of the box, this is null for a Window control.

There are two options for this problem. You can either set the DataContext explicitely in the code-behind or the XAML

// In XAML
<Window DataContext={Binding RelativeSource={RelativeSource Self}}>

or

// In the code-behind
DataContext = this;

Another problem is that the binding is applied at initialization. Initially, your properties are empty. After the InitializeComponent phase, the controls will "bind" to the properties (which are empty). When you set your properties afterward, the controls have no way to know it has changed. There are two mechanism to allow this. On the control level, you can make these properties as DependencyProperty or implement the INotifyPropertyChanged interface and raise the changes. If you want to go the INPC route, you can implement your properties and Window as such:

public partial class MainWindow : INotifyPropertyChanged
{
    private string firstString;
    private string secondString;
    private string thirdString;
    private string fourthString;

    public string FirstString
    {
        get { return firstString; }
        set
        {
            firstString = value;
            RaisePropertyChanged("FirstString");
        }
    }

    public string SecondString
    {
        get { return secondString; }
        set
        {
            secondString = value;
            RaisePropertyChanged("SecondString");
        }
    }

    public string ThirdString
    {
        get { return thirdString; }
        set
        {
            thirdString = value;
            RaisePropertyChanged("ThirdString");
        }
    }

    public string FourthString
    {
        get { return fourthString; }
        set
        {
            fourthString = value;
            RaisePropertyChanged("FourthString");
        }
    }

    public MainWindow()
    {
        DataContext = this;
        InitializeComponent();

        FirstString = "First";
        SecondString = "Second";
        ThirdString = "Third";
        FourthString = "Fourth";
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    private void RaisePropertyChanged(string propertyName)
    {
        var handlers = PropertyChanged;

        handlers(this, new PropertyChangedEventArgs(propertyName));
    }
}
3
  • there is no need to do this, as code is in behind the xaml, and it will notify automatically when context is change...
    – A.T.
    Aug 5, 2013 at 14:22
  • 4
    @Arun I'm not following your logic. If the properties are not INPC and not Dependency Properties, a change to the property will not be reflected to the UI. In this simple case, setting the DataContext = this after setting the property will work because DataContext is a dependency property. But any further change in code will not be reflected. Aug 5, 2013 at 14:25
  • @oimitro This is a very contrived example and will work. But beware that it is far from best practice. You would usually have another object (that we call a View Model) that implements the interface and that object will be assigned to your View's (Window in this case) DataContext. You can look this CodeProject entry if you want to read more about the MVVM pattern in the context of WPF. Aug 5, 2013 at 16:08
4

Unless specified otherwise, the path of the binding is relative to the DataContext of the element. In your case, I suspect you didn't specify a DataContext at all...

Since the properties are declared in the MainWindow class itself, the easiest fix is to add:

DataContext = this;

at the end of the constructor.

3
  • I used DataContext = this; but still nothing.
    – oimitro
    Aug 5, 2013 at 14:11
  • Move InitializeComponent(); to the bottom of your constructor, then you should at least see something. Nicolas is right, though.
    – Golvellius
    Aug 5, 2013 at 14:14
  • where your writing DataContext = this; move it to bottom
    – A.T.
    Aug 5, 2013 at 14:15
3

it should be something like this to work,

<Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <TextBlock x:Name="First" Text="{Binding FirstString}" Grid.Row="0"/>
            <TextBlock x:Name="Second" Text="{Binding SecondString}" Grid.Row="1"/>
            <TextBlock x:Name="Third" Text="{Binding ThirdString}" Grid.Row="2"/>
            <TextBlock x:Name="Fourth" Text="{Binding FourthString}" Grid.Row="3"/>
        </Grid>

and c# code will be like,

public string FirstString { get; set; }
public string SecondString { get; set; }
public string ThirdString { get; set; }
public string FourthString { get; set; }

public MainWindow()
{
    InitializeComponent();    

    FirstString = "First";
    SecondString = "Second";
    ThirdString = "Third";
    FourthString= "Fourth";
    this.DataContext = this;  //here you set the context to current instance of window

}
3

Since your aren't notifying that FirstString, SecondString, ThirdString and FourthString changed, the change will not be reflected in the UI. You can either implement INotifyPropertyChanged, or deal with DependencyProperty

Set your Datacontext, too.

IMHO DependencyProperty is better for this use. Here is an example :

public partial class MainWindow : Window
{
    #region Public
    public string FirstString
    {
        get { return (string)GetValue(FirstStringProperty); }
        set { SetValue(FirstStringProperty, value); }
    }
    public string SecondString
    {
        get { return (string)GetValue(SecondStringProperty); }
        set { SetValue(SecondStringProperty, value); }
    }
    public string ThirdString
    {
        get { return (string)GetValue(ThirdStringProperty); }
        set { SetValue(ThirdStringProperty, value); }
    }
    public string FourthString
    {
        get { return (string)GetValue(FourthStringProperty); }
        set { SetValue(FourthStringProperty, value); }
    }

    #region Dependency Properties
    public static readonly DependencyProperty FirstStringProperty = DependencyProperty.Register("FirstString", typeof(string), typeof(MainWindow), new PropertyMetadata("default value"));
    public static readonly DependencyProperty SecondStringProperty = DependencyProperty.Register("SecondString", typeof(string), typeof(MainWindow), new PropertyMetadata("default value"));
    public static readonly DependencyProperty ThirdStringProperty = DependencyProperty.Register("ThirdString", typeof(string), typeof(MainWindow), new PropertyMetadata("default value"));        
    public static readonly DependencyProperty FourthStringProperty = DependencyProperty.Register("FourthString", typeof(string), typeof(MainWindow), new PropertyMetadata("default value"));
    #endregion
    #endregion

    public MainWindow()
    {
        InitializeComponent();    

        FirstString = "First";
        SecondString = "Second";
        ThirdString= "Third";
        FourthString= "Fourth";

        this.DataContext = this;
    }
}
1
  • You are missing a 2nd quotationmark at ThirdString= "Third inside of your ctor example
    – Mafii
    Jun 23, 2016 at 9:58
3

I would suggest that you create another class MainWindowViewModel.

public class MainWindowViewModel
{
    public string FirstString { get; set; }
    public string SecondString { get; set; }
    public string ThirdString { get; set; }
    public string FourthString { get; set; }

    public MainWindowViewModel()
    {    
        FirstString = "First";
        SecondString = "Second";
        ThirdString= "Third";
        FourthString= "Fourth";
    }
}

Then set the DataContext of the MainWindow object before calling show on the window class.

MainWindow wnd = new MainWindow();
wnd.DataContext = new MainWindowViewModel();
wnd.Show();

You can do this last bit by removing StartupUri="MainWindow.xaml" from your App.xaml and create and show the main window manually by overriding OnStartup in App.xaml.cs.

2
  • @Sinon Belanger There is no InitializeComponent() method on the class MainWindowViewModel.
    – Zenchovey
    Aug 5, 2013 at 14:29
  • Oh. Sorry. Didn't realize it was a view model. Removing my comment. Aug 5, 2013 at 15:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.