单元格模板化 DataGrid 中的数据绑定不起作用

Databinding within Cell templated DataGrid not working

我尝试将 List<string> 属性 SubscribedSymbols 绑定到 class 对象 StrategySubscription 作为 List<StrategySubscription> 的一部分到每个组合框DataGrid 中特定列的单元格,但无法使数据绑定起作用。

自动列生成器工作并将值填充到网格中。所以,我确定数据存在。

我附上了 xaml 代码和数据对象以及当前输出的屏幕截图。

你能帮忙让数据绑定正常工作吗?我希望 SubscribedSymbols 中的字符串集合填充到模板化列中每个单元格的组合框中。

<DataGrid ItemsSource="{Binding StrategySubscriptions}" AutoGenerateColumns="False">

                    <DataGrid.Columns>

                        <DataGridTextColumn Header="Strategy ID" Binding="{Binding StrategyId}"/>
                        <DataGridTextColumn Header="Strategy Name " Binding="{Binding StrategyName}"/>
                        <DataGridTextColumn Header="Strategy Capitalization" Binding="{Binding CapitalAllocation}"/>
                        <DataGridComboBoxColumn Header="Symbol Subscriptions" ItemsSource="{Binding SubscribedSymbols, RelativeSource={RelativeSource TemplatedParent}}"/>

                    </DataGrid.Columns>

                </DataGrid>

public class StrategySubscription
    {
        public Guid StrategyId { get; set; }
        public string StrategyName { get; set; }
        public int CapitalAllocation { get; set; }
        public List<string> SubscribedSymbols { get; set; }

        public StrategySubscription(string strategyName, Guid strategyId, int capitalAllocation, List<SymbolSubscription> symbolSubscriptions)
        {
            StrategyName = strategyName;
            StrategyId = strategyId;
            CapitalAllocation = capitalAllocation;
            SubscribedSymbols = symbolSubscriptions.Select(x => x.Symbol.SymbolId).ToList();
            //SubscribedSymbols = String.Join(", ", symbolSubscriptions.Select(x => x.Symbol.SymbolId).OrderBy(x=>x));
        }
    }

试试这个:

...
<DataGridComboBoxColumn Header="Symbol Subscriptions" >
    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding Path=SubscribedSymbols}" />
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding Path=SubscribedSymbols}" />
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
...

尝试使用模板列来更好地控制它:

<DataGridTemplateColumn Header="Symbol Subscriptions">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox ItemsSource="{Binding SubscribedSymbols}"/>
        </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

问题的原因是 DataGridColumns 不是可视化树的一部分。在这里查看更多解释:http://blogs.msdn.com/b/vinsibal/archive/2008/12/17/wpf-datagrid-dynamically-updating-datagridcomboboxcolumn.aspx