DataGridTemplateColumn with ComboBox and TextBlock



我正在我的应用程序中动态创建一个datagridtemplatecoluml。这样做的原因是因为我有一个TabControl,当用户想要添加一个新的选项卡时,TabItem中就会创建一个Datagrid。下面是我到目前为止创建我的列的代码:

    private DataGridTemplateColumn GetAccountColumn()
    {
        DataGridTemplateColumn accountColumn = new DataGridTemplateColumn();
        accountColumn.Header = "Account";
        string xaml = @"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">
                            <TextBlock Text=""{Binding Path='Account', Mode=OneWay}"" />
                        </DataTemplate>";
        StringReader stringReader = new StringReader(xaml);
        XmlReader xmlReader = XmlReader.Create(stringReader);
        accountColumn.CellTemplate = (DataTemplate)XamlReader.Parse(xaml);
        xaml = @"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">
                     <ComboBox ItemsSource=""{DynamicResource accounts}"" Text=""{Binding Path='Account', Mode=OneWay}"" Height=""23"" IsTextSearchEnabled=""True""/>
                 </DataTemplate>";
        stringReader = new StringReader(xaml);
        xmlReader = XmlReader.Create(stringReader);
        accountColumn.CellEditingTemplate = (DataTemplate)XamlReader.Parse(xaml);
        return accountColumn;
    }

组合框完美地填充了项目。从上面的代码中可以看到,itemsource被绑定到一个可观察的字符串集合。我在运行时通过以下方式填充资源:

Resources["accounts"] = this.Account;

一切似乎都很好地工作,除了我在组合框中进行选择并且组合框失去焦点之后,我选择的项目不显示在TextBlock中。如何使这个项目出现在TextBlock中?我尝试将模式设置为双向,但我得到一个错误,说"双向或OneWayToSource绑定不能在类型为'System.Data.DataRowView'的只读属性'Account'上工作。"

您需要将ComboBoxSelectedItem属性绑定到Account,而不是Text属性:

 xaml = @"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">
                 <ComboBox ItemsSource=""{DynamicResource accounts}"" SelectedItem=""{Binding Path='Account'}"" Height=""23"" IsTextSearchEnabled=""True""/>
             </DataTemplate>";

编辑

另一个问题是:

我尝试将模式设置为双向,但我得到一个错误,说"双向或OneWayToSource绑定不能在类型为'System.Data.DataRowView'的只读属性'Account'上工作。"

如果Account属性是只读的,你不能改变它,那么编辑它就没有意义了。你需要让它可写,否则你不能从UI改变它,你不能存储任何数据。

最新更新