2015-02-25 3 views
0

У меня есть UserControl, в котором у меня есть DataGridНевозможно привязать к UserControl свойство в главном окне

public partial class UserControl1 : UserControl 
{ 
    public object SelectedItem 
    { 
     get { return GetValue(SelectedItemProperty); } 
     set { SetValue(SelectedItemProperty, value); } 
    } 

    public static readonly DependencyProperty SelectedItemProperty = DataGrid.SelectedItemProperty.AddOwner(typeof(UserControl1)); 

    } 
    <DataGrid ItemsSource="{Binding MySource}" 
       AutoGenerateColumns="True" 
           SelectedItem="{Binding Path=SelectedItem,RelativeSource={RelativeSource FindAncestor, 
             AncestorType=my:UserControl1, 
             AncestorLevel=1}}"/> 

В моей MainWindow

<WpfApplication3:UserControl1 x:Name="myControl" 
           Grid.Row="0" SelectedItem="{Binding CurrentItem}" /> 

и в моем MainWindowвид модели

public object CurrentItem 
    { 

     get { return currentItem; } 
     set 
     {  currentItem = value; 
       OnPropertyChanged("CurrentItem"); 
     } 
    } 

Я не могу получить currentItem.

+0

да я уже сделал это – Rohit

ответ

1

Вы устанавливаете DataContext UserControl для себя, поэтому, когда вы устанавливаете привязку для SelectedItem, вы фактически просите его искать CurrentItem в DataContext UserControl вместо вашей основной модели окна окна.

Дайте главное окно имя и использовать связывание:

{Binding DataContext.CurrentItem, ElementName=windowName} 
Смежные вопросы