无法绑定到 Main Window 中的用户控件 属性
Cannot bind to usercontrol property in Main Window
我有 usercontrol,其中我有 datagrid
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");
}
}
我无法获取当前项目。
您正在将 UserControl 的 DataContext 设置为其自身,因此当您为 SelectedItem 设置绑定时,您实际上是在要求它在 UserControl 的 DataContext 而不是主 window 视图模型上查找 CurrentItem .
给 Main Window 命名并使用绑定:
{Binding DataContext.CurrentItem, ElementName=windowName}
我有 usercontrol,其中我有 datagrid
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");
}
}
我无法获取当前项目。
您正在将 UserControl 的 DataContext 设置为其自身,因此当您为 SelectedItem 设置绑定时,您实际上是在要求它在 UserControl 的 DataContext 而不是主 window 视图模型上查找 CurrentItem .
给 Main Window 命名并使用绑定:
{Binding DataContext.CurrentItem, ElementName=windowName}