質問

I am creating a DataGridTemplateColumn dynamically in my application. The reason for this, is because I have a TabControl and when the user wants to add a new Tab, a Datagrid is created in the TabItem. Here is the code that I have so far to create my column:

    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;
    }

The combobox is populated with items perfectly. As you can see from the code above, the itemsource is bound to an observable collection of strings. I populate the resource during runtime by the following:

Resources["accounts"] = this.Account;

Everything seems to work nicely, EXCEPT after I make a selection in the combobox and the combobox loses focus, the item I selected is not displayed in the TextBlock. How can I make this item appear in the TextBlock? I tried setting the mode to TwoWay but I get an error saying "A TwoWay or OneWayToSource binding cannot work on the read-only property 'Account' of type 'System.Data.DataRowView'."

役に立ちましたか?

解決

You need to bind the SelectedItem property of your ComboBox to Account and not the Text property:

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

Edit

Another problem is this:

I tried setting the mode to TwoWay but I get an error saying "A TwoWay or OneWayToSource binding cannot work on the read-only property 'Account' of type 'System.Data.DataRowView'."

If the Account property is readonly you can't change it then editing it makes no sense at all. You need to make it writable otherwise you can't change it from the UI and you can't store any data.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top