【问题标题】:ItemSource Binding on ComboBox inside a DataGrid在 DataGrid 内的 ComboBox 上的 ItemSsource 绑定
【发布时间】:2017-09-08 14:36:04
【问题描述】:

DataGrid 中的 ComboBox 没有被列表填充。 我认为 ItemSource Path 有问题:

查看(DataGrid 的 xaml 代码):

<DataGrid CanUserAddRows="True" ItemsSource="{Binding Path=GridCollection, Mode=TwoWay}" AutoGenerateColumns="False" IsReadOnly="False">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Column 1">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ComboBox ItemsSource="{Binding Path=DataContext.ComboBoxList}" BorderThickness="0" BorderBrush="Transparent" SelectedValue="{Binding Col1, Mode=TwoWay}"/>
                    </ComboBox>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Header="Column 2" Width="170" Binding="{Binding Col2, Mode=TwoWay}"/>
</DataGrid>

查看模型(我为 ItemModel 创建了一个可观察的集合,当我更新 Text Column 的值并将值分配给 Model 对象时,这工作正常):

public ObservableCollection<ItemModel> GridCollection
{
    get
    {
        return this.gridCollection;
    }
    set
    {
        this.gridCollection = value;
        base.RaisedPropertyChanged("GridCollection");
    }
}

public List<string> ComboBoxList
{
    get
    {
        return this.comboBoxList;
    }
    set
    {
        this.comboBoxList = value;
        base.RaisedPropertyChanged("GridList");
    }
}

public MultiValueViewModel(string data)
{
    this.GridCollection = new ObservableCollection<ItemModel>(); 
    this.GridCollection.Add(new ItemModel("ABC", 0));
    this.ComboBoxList = new List<string>();
    //Add items to list
}

模型(模型包含一个具有 2 个属性的类):

public class ItemModel
{
    public ItemModel(string col1, double col2)
    {
        this.Col1 = col1;
        this.Col2 = col2;
    }

    public string Col1 { get; set; }

    public double Col2 { get; set; }
}

我已尝试使用 Path=ComboBoxList 和 DataContext.ComboBoxList - bit 都不起作用。

【问题讨论】:

  • 调试时检查Output窗口中的绑定错误。您的目标是零错误。

标签: c# wpf mvvm


【解决方案1】:

试试这个:

<ComboBox ItemsSource="{Binding Path=DataContext.ComboBoxList, RelativeSource={RelativeSource AncestorType=DataGrid}}" BorderThickness="0" BorderBrush="Transparent" SelectedValue="{Binding Col1, Mode=TwoWay}"/>

ComboBoxDataContext 默认为ItemModel,因此您应该绑定到父DataGridDataContext 的属性。您可以按照上述使用{RelativeSource} 来执行此操作。

【讨论】:

    猜你喜欢
    • 2020-01-30
    • 2011-02-28
    • 2015-04-07
    • 1970-01-01
    • 2013-06-30
    • 2014-12-12
    • 2013-10-22
    • 2013-01-14
    • 2015-10-06
    相关资源
    最近更新 更多