我希望能够手动设置用于ItemControl项目的容器的DataContext吗?
这可能吗?
(我不希望在集合发生变化的情况下使用ItemsSource的转换器进行此操作,理想情况下我希望能够在某种自定义ItemsControl中执行此操作,因为它会经常使用)
<l:CustomItemsControl ItemsSource="{Binding Items}"/>
public partial class MainWindow : Window
{
public ObservableCollection<object> Items { get; private set; }
public MainWindow()
{
Items = new ObservableCollection<object>() { 6, "Dog", DateTime.Now };
DataContext = this;
InitializeComponent();
}
}
我以为我可以做类似下面的事情,但它没有任何影响,因为看起来之后再次设置了DataContext
public class CustomItemsControl : ItemsControl
{
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
base.PrepareContainerForItemOverride(element, item);
var presenter = element as ContentPresenter;
presenter.DataContext = 5;
// below would be some binding that is set up on some dynamic property of item
// presenter.SetBinding(ContentPresenter.DataContextProperty, new Binding());
}
}