我创建了一个UserControl,该用户控件在其背后的代码中具有依赖项属性:
UnitsViewer.xaml.cs
public partial class UnitsViewer : UserControl
{
public ObservableCollection<Unit> Units
{
get { return (ObservableCollection<Unit>)GetValue(UnitsProperty); }
set { SetValue(UnitsProperty, value); }
}
public static readonly DependencyProperty UnitsProperty = DependencyProperty.Register("Units", typeof(ObservableCollection<Unit>), typeof(UnitsViewer), new PropertyMetadata(new ObservableCollection<Unit>()));
public UnitsViewer()
{
DataContext = this;
InitializeComponent();
}
}
UnitsViewer.xaml
<TextBlock Text="{Binding Path=Units.Count}" />
对于我的MainWindow,我将其DataContext设置为MainWindowViewModel,并尝试将UnitWindow属性从MainWindowViewModel绑定到UserControl中的Units:
MainWindowViewModel.cs
public class MainWindowViewModel : BaseModel
{
public ObservableCollection<Unit> Units { get; set; }
}
MainWindow.xaml
<controls:UnitsViewer Units="{Binding Path=Units}" />
MainWindowViewModel中的单元只有一个元素,但输出为 0 。
关于我可能会缺少的任何想法吗?