将UserControl绑定到WPF中的MainWindow元素

时间:2016-09-16 16:23:31

标签: c# wpf

我是WPF中的新手并且有问题堆叠。我有DataContext绑定到ListView所选项目的网格。所有在一个XAML文件中它都可以工作。如何在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>

主窗口:

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

1 个答案:

答案 0 :(得分:1)

你不能。 booksGrid在用户控件的上下文中不存在。

相反,在DependencyProperty

上声明propdp(摘录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));

现在您可以将所选值绑定到它:

主窗口:

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

在UserControl本身中,您应该在依赖项属性的属性更改回调中手动设置正确的属性。绑定到代码属性是不安全的,因为框架永远不会调用它的setter。

相关问题