自定义控件,将DataContext级联到集合中的子元素

Jan*_*kan 7 c# wpf datacontext custom-controls

我正在尝试创建自定义用户控件,其功能与DataGrid类似(但DataGrid不是正确的选项).

我想要实现的是这样的:

<my:CustomList ItemsSource="{Binding Items}">
    <my:CustomList.Columns>
        <my:Column Width="60" Binding="{Binding MyCustomProperty}" />
    </my:CustomList.Columns>
</my:CustomList>
Run Code Online (Sandbox Code Playgroud)

其中Items将来自ViewModel(例如),如下所示:

public ObservableCollection<Item> Items { get; set; }

public class Item
{
    public string MyCustomProperty { get; set; }
    public string MyAnotherCustomProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是绑定到MyCustomProperty.

如果我从DataGrid继承我的自定义控件并使用它的列,DataContext就会从ItemsSource流向Bindings就好了.我想对我的自定义控件执行相同操作,该控件不从DataGrid继承.DataGrid.Columns从ItemsSource获取上下文背后的魔力是什么?

编辑: 让我再问一下这个问题:

如果我实现自定义DataGridColumn

public class MyDataGridColumn : DataGridBoundColumn
{
    private Binding _bindingSubText;

    public Binding BindingSubText
    {
        get
        {
            return _bindingSubText;
        }
        set
        {
            if (_bindingSubText == value) return;
            var oldBinding = _bindingSubText;
            _bindingSubText = value;
            OnBindingChanged(oldBinding, _bindingSubText);
        }
    }

    protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
    {
        var textTextBlock = new TextBlock();
        var bindingText = Binding ?? new Binding();
        textTextBlock.SetBinding(TextBlock.TextProperty, bindingText);

        var textSubTextBlock = new TextBlock();
        var bindingSubText = BindingSubText ?? new Binding();
        textSubTextBlock.SetBinding(TextBlock.TextProperty, bindingSubText);

        var stackPanel = new StackPanel() { Orientation = Orientation.Vertical };
        stackPanel.Children.Add(textTextBlock);
        stackPanel.Children.Add(textSubTextBlock);

        return stackPanel;
    }

    protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
    {
        // I don't want to edit elements
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

并尝试在XAML中使用它,如下所示:

<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <my:MyDataGridColumn Binding="{Binding MyCustomProperty}" BindingSubText="{Binding MyAnotherCustomProperty}" />
    </DataGrid.Columns>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)

绑定BindingSubText属性仍然会带有DataGrid父级的DataContext,为我提供Items.MyAnotherCustomProperty在设计器中会有摆动,但它可以正常运行(因为动态绑定).我的问题是,当其他人将使用这个自定义DataGridColumn时,他/她需要知道这一点,并且对于绑定会有"错误的"IntelliSense.

如何设置DataGridColumn的Binding属性的上下文,以便IntelliSense按预期工作?

MDo*_*bie -1

我认为,DataGrid 的祖先之一可以处理该问题(可能是 ItemsControl)。如果您的控件不是从 ItemsControl 派生的,您必须手动处理此问题(在向控件添加新列时显式设置其数据上下文)。

现在我看到你的控件也是从 ItemsControl 派生的。那么我建议手动处理。