如何将MainWindow上的TextBox绑定到UserControl上的DataGrid?

时间:2016-11-21 12:24:03

标签: wpf data-binding datagrid user-controls

我在MainWindow上有TextBox和UserControl。 UserControl包含DataGrid。我使用下一个绑定:

<TextBox x:Name="TextBoxOnMainWindow" Height="23" TextWrapping="Wrap" Text="{Binding ElementName=MyUserControlWithGrid, Path=GridOnMyUserControl.SelectedItem.name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="200"/>

它不起作用。如何解决?

1 个答案:

答案 0 :(得分:0)

您无法访问UserControl的数据网格。您可以轻松地从DataGrid代理所选项目:

/// <summary>
///     Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1
{
    public static readonly DependencyProperty SelectedDataGridItemProperty = DependencyProperty.Register(
        "SelectedDataGridItem", typeof (object), typeof (UserControl1), new PropertyMetadata(default(object)));

    public UserControl1()
    {
        InitializeComponent();
    }

    public object SelectedDataGridItem
    {
        get { return GetValue(SelectedDataGridItemProperty); }
        set { SetValue(SelectedDataGridItemProperty, value); }
    }

    private void MyAwesomeDataGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        SelectedDataGridItem = MyAwesomeDataGrid.SelectedItem;
    }
}

XAML:

<UserControl x:Class="MyApplication.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             d:DesignHeight="300"
             d:DesignWidth="300"
             mc:Ignorable="d">
    <DataGrid x:Name="MyAwesomeDataGrid" SelectionChanged="MyAwesomeDataGrid_OnSelectionChanged"/>
</UserControl>

现在,此代码将起作用:

    <TextBox x:Name="TextBoxOnMainWindow"
             Text="{Binding ElementName=MyUserControlWithGrid,
                            Path=SelectedDataGridItem.name}"
             TextWrapping="Wrap" />