DataTable未绑定到DataGrid的DataContext

时间:2012-12-04 12:49:33

标签: c# wpf datagrid observablecollection datacontext

我有DataGrid,请按照XAML:

    <DataGrid ItemsSource="{Binding Path=propCollection}"
              SelectedItem="{Binding Path=SelectProp, Mode=TwoWay}"
              Margin="-1,159,0,0" 
              RowDetailsVisibilityMode="Visible" 
              AreRowDetailsFrozen="False" 
              CanUserReorderColumns="False" 
              CanUserSortColumns="True" 
              CanUserResizeRows="False"  
              SelectionUnit="FullRow" 
              AlternatingRowBackground="{x:Null}" 
              SelectionChanged="dgProprietarios_SelectionChanged"
              AlternationCount="0"
              Height="200" 
              HorizontalAlignment="Left"
              Name="dgProprietarios" 
              VerticalAlignment="Top" 
              Width="645" 
              AutoGenerateColumns="False">
                 <...Columns...>
    </DataGrid>

在我的 Window_Loaded 上,我执行以下操作:

dgProprietarios.DataContext = new ProprietariosViewModel(new Dictionary<string, string>());

我的 ProprietariosViewModel 如下:

public CollectionProprietarios propCollection { get; set; }

public ProprietariosViewModel(Dictionary<string, string> Where)
{
    propCollection = new CollectionProprietarios(Where);
}

CollectionProprietarios 类继承 ObservableCollection 并具有以下代码:

    public CollectionProprietarios(Dictionary<string, string> Where)
    {
        Add(new Dados(Where));
    }

    public new void Add(Dados dados)
    {
        base.Add(dados);
    }

班级 Dados 包含以下代码:

public DataTable ProprietariosRetorno { get; private set; }

public Dados(Dictionary<string, string> Where)
{

    var ado = new ADO();
    ProprietariosRetorno = ado.RetornaSelect(MontaQuery(Where));

}

函数 MontaQuery 只创建一个包含SELECT子句的字符串, RetornaSelect 执行此查询。

ADO ,当instanciated只创建数据库和表(如果它不存在)。

问题是,所有这些都有效。在调试时,我可以检索DataContext中的值,它包含带有值的DataTable。但由于某种原因,程序运行时它不会出现在DataGrid上。

所以问题是,我做错了什么?

1 个答案:

答案 0 :(得分:1)

尝试使用

dgProprietarios.DataContext = new ProprietariosViewModel(new Dictionary<string, string>());
dgProprietarios.Items.Refresh();