Search code examples
c#wpfdata-binding

What precisely is required for this WPF binding to update?


I have a treeview to which I've added behaviours that allows me to bind to the currently selected item (a dependency property I've named SelectedCourse). This appears to work just fine, as I can pause the program and confirm that the value of the selected item is changing:

Here is the XAML binding:

<TextBox TextWrapping="Wrap"
         Text="{Binding SelectedCourse.Description}">
</TextBox>

And as you can see, nothing happens in the UI when SelectedCourse gets updated:

(The red box on the right is the textbox. The red outline comes from Snoop.)

BindableCourse inherits from DependencyObject, and Description is a dependency property:

public class BindableCourse : DependencyObject
{
    public static DependencyProperty DescriptionProperty = DependencyProperty.Register(
            "Description",
            typeof(string),
            typeof(BindableCourse));

    public string Description
    {
        get { return (string)GetValue(DescriptionProperty); }
        set { SetValue(DescriptionProperty, value); }
    }
}

Now, if I look the textbox element in Snoop, SelectedCourse.Description appears in the textbox as desired.

Afterward, I can't get the textbox to change; even by, for example, changing SelectedCourse -- and I've checked and SelectedCourse does get changed when I select a new element -- and then closing Snoop, reopening it, and then reinspecting the textbox.

wtf is going on?


Solution

  • Instead of using your own custom binding, I think you can do something like the following:

    <TextBox TextWrapping="Wrap"
         Text="{Binding ElementName=TreeViewName, Path=SelectedValue.Description}">
    </TextBox>
    

    The selected value will change depending on the tree view selection. "TreeViewName" is the name of the your treeview using the x:Name attribute.