Cell模板化DataGrid中的数据绑定无法正常工作

时间:2015-02-28 12:54:11

标签: c# wpf data-binding datagrid

我尝试将List<string>属性SubscribedSymbols作为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));
        }
    }

enter image description here

2 个答案:

答案 0 :(得分:2)

尝试使用模板列对其进行更多控制:

<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

答案 1 :(得分:1)

试试这个:

...
<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>
...