双向绑定不适用于自定义DataGridTemplateColumn

时间:2019-09-27 16:32:30

标签: c# wpf xaml datagrid

我一直在尝试为可显示值数组的自定义DataGrid列创建解决方案。单向绑定适用于下面的解决方案,但是双向绑定不会更新源。任何想法将不胜感激。

DataGridBoundTemplateColumn.cs:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace CustomColumnDemo
{
    public class DataGridBoundTemplateColumn : DataGridBoundColumn
    {
        public DataTemplate CellTemplate { get; set; }
        public DataTemplate CellEditingTemplate { get; set; }

        protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) => Generate(dataItem, CellTemplate);
        protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) => Generate(dataItem, CellEditingTemplate);

        private FrameworkElement Generate(object dataItem, DataTemplate template)
        {
            var contentControl = new ContentControl { ContentTemplate = template, Content = dataItem };
            BindingOperations.SetBinding(contentControl, ContentControl.ContentProperty, Binding);
            return contentControl;
        }
    }
}

DataGridArrayColumn.xaml:

<local:DataGridBoundTemplateColumn
    x:Class="CustomColumnDemo.DataGridArrayColumn"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:CustomColumnDemo">
    <local:DataGridBoundTemplateColumn.CellTemplate>
        <ItemContainerTemplate>
            <ItemsControl ItemsSource="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Horizontal" />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <ItemContainerTemplate>
                        <TextBox Text="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
                    </ItemContainerTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        <ItemContainerTemplate>
    </local:DataGridBoundTemplateColumn.CellTemplate>
</local:DataGridBoundTemplateColumn>

DataGridArrayColumn.xaml.cs:

namespace CustomColumnDemo
{
    public partial class DataGridArrayColumn : DataGridBoundTemplateColumn
    {
        public DataGridArrayColumn()
        {
            InitializeComponent();
        }
    }
}

0 个答案:

没有答案