1

I am new to object binding and I don' succeed to make it work.

I have a xaml window with the following textbox:

<Grid x:Name="gr_main" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="180,65,0,0" DataContext="{Binding currentproj}">
<Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>

<TextBox Grid.Row="0" Grid.Column="2" x:Name="txt_localdir"  Height="25" TextWrapping="Wrap" Width="247" IsEnabled="False" Text="{Binding Path=Localdir, UpdateSourceTrigger=PropertyChanged}"/>

In the cs code of the main window, I define an instance of my Project class, called currentproj, as follows:

public partial class MainWindow : Window{
Project currentproj;

public MainWindow()
{            
    currentproj = new Project();
    InitializeComponent();
}}

The project class (defined in a Project.cs file) is as follows:

public partial class Project : Component, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

private string _localdir;
public string Localdir
{
    get { return _localdir; }
    set
    {
        if (value != _localdir)
        {
            _localdir = value;
            NotifyPropertyChanged("Localdir");
        }
    }
}

public Project()
{
    InitializeComponent();
}

public Project(IContainer container)
{
    container.Add(this);

    InitializeComponent();
}}

However, even if I am binding the textbox.text attribute to the Localdir path of the currentproj object, the textbox is never updated. I see the PropertyChanged event is alwais null when I set the value of Localdir, but I don't understand why.

1
  • Have you tried setting Mode=TwoWay within your Binding in XAML? Commented Jun 6, 2018 at 15:07

1 Answer 1

1

Data binding works on the DataContext. The Grid's DataContext is not set correctly, this should be removed.

so the Grid definition should be:

<Grid x:Name="gr_main" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="180,65,0,0">

Setting the Window DataContext to currentProj is done by:

public partial class MainWindow : Window{
Project currentproj;

public MainWindow()
{            
    currentproj = new Project();
    DataContext = currentproj;
    InitializeComponent();
}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.