Rodion Rodion - 2 months ago 26
C# Question

Bind UserControl to MainWindow element in WPF

I'm new in WPF and stack with problem. I have grid with

DataContext
bind to
ListView
selected item. It's work when all in one XAML file. How can i save binding after moving grid in
UserControl
?

UserControl:

<UserControl x:Class="Books.Views.BookView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Books.Views"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid DataContext="{Binding SelectedValue, ElementName=booksGrid}">
...
</Grid>
</UserControl>


MainWindow:

...
<ListView x:Name="booksGrid" ItemsSource="{Binding}">
...
<ContentControl Name="infoControl"
Grid.Row="0"
Grid.Column="1"
Content="{Binding}" />

Answer

You can't. booksGrid doesn't exist in the context of the user control.

Instead, declare a DependencyProperty (snippet propdp) on the UserControl

    public Book Book
    {
        get { return (Book)GetValue(BookProperty); }
        set { SetValue(BookProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Book.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty BookProperty =
        DependencyProperty.Register("Book", typeof(Book), typeof(BookView), new PropertyMetadata(null));

Now you can bind your selected value to it:

MainWindow:

<BookView Book="{Binding SelectedValue, ElementName=booksGrid}"/>

In the UserControl itself you should manually set the correct properties in the property changed callback of the dependency property. Binding to the code property is unsafe as the setter for it is never called by the framework.