【问题标题】:DataGrid not populating with bindingDataGrid 未填充绑定
【发布时间】:2017-08-07 14:24:27
【问题描述】:

我正在尝试使用 SQL 查询填充 DataGrid,然后能够过滤数据网格。到目前为止,我有这个:

XAML

<Window x:Name="ResultsWindow" x:Class="PixsellSheet.PixsellOrders"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:PixsellSheet"
    mc:Ignorable="d" Height="721.175" Width="1549.21" Title="edit" WindowStartupLocation="CenterScreen">
<Grid>
    <DataGrid x:Name="Grid" HorizontalAlignment="Stretch" Height="Auto" Margin="20,55,20,40" VerticalAlignment="Stretch" Width="Auto" ItemsSource="{Binding DataGridColletion}">
        <DataGrid.Resources>
            <ContextMenu x:Key="DataGridColumnHeaderContextMenu">
                <MenuItem Header="Filter" Click="MenuItem_Click"/>
            </ContextMenu>
            <Style TargetType="{x:Type DataGridColumnHeader}">
                <Setter Property="ContextMenu" Value="{StaticResource DataGridColumnHeaderContextMenu}"/>
            </Style>
        </DataGrid.Resources>
    </DataGrid>
    <Button x:Name="BtnBack" HorizontalAlignment="Left" Margin="20,10,0,0" VerticalAlignment="Top" Width="30" Click="BtnBack_Click" Padding="20,0,5,0">
        <Button.Template>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid>
                    <Image Name="Normal" Source="back.png"/>
                    <Image Name="Pressed" Source="back_pressed.png"/>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsPressed" Value="True">
                        <Setter TargetName="Normal" Property="Visibility" Value="Hidden"/>
                        <Setter TargetName="Pressed" Property="Visibility" Value="Visible"/>
                    </Trigger>
                    <Trigger Property="IsPressed" Value="False">
                        <Setter TargetName="Normal" Property="Visibility" Value="Visible"/>
                        <Setter TargetName="Pressed" Property="Visibility" Value="Hidden"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Button.Template>
    </Button>
    <TextBox Height="27" Margin="0,10,20,0" TextWrapping="Wrap" VerticalAlignment="Top" HorizontalAlignment="Right" Width="524" Name="FilterBox" Padding="5,0,20,0"/>
    <Label Content="Filter:" HorizontalAlignment="Right" Margin="0,10,550,0" VerticalAlignment="Top" Padding="5,0,5,0"/>
    <Grid HorizontalAlignment="Left" Height="25" Margin="60,10,0,0" VerticalAlignment="Top" Width="20" />
</Grid>

C#

public partial class PixsellOrders : Window, INotifyPropertyChanged
{
    public ICollectionView _dataGridCollection;
    private string _filterString;

    public ICollectionView DataGridCollection
    {
        get { return _dataGridCollection; }
        set { _dataGridCollection = value; NotifyPropertyChanged("DataGridCollection"); }
    }

    public PixsellOrders(string windowTitle)
    {
        InitializeComponent();

        string query = "";

        ResultsWindow.Title = windowTitle;

        Console.WriteLine(windowTitle);

        if (windowTitle == "PixSell Orders All")
        {
            query = "EXEC Reporting.dbo.Pixsell_Orders_All";
        }
        else if (windowTitle == "PixSell Orders Eday")
        {
            query = "EXEC Reporting.dbo.Pixsell_Orders_Eday";
        }

        Console.WriteLine(query);

        try
        {
            DataTable pixsellOrders = SqlConnect(query);

            foreach (DataColumn column in pixsellOrders.Columns)
            {
                column.ReadOnly = true;

                if (column.ColumnName == "Person" && windowTitle != "PixSell Orders All")
                {
                    pixsellOrders.Columns["Person"].ReadOnly = false;
                }
                else if (column.ColumnName == "Sales Notes" && windowTitle != "PixSell Orders All")
                {
                    pixsellOrders.Columns["Sales Notes"].ReadOnly = false;
                }
            }

            DataGridCollection = CollectionViewSource.GetDefaultView(pixsellOrders.AsEnumerable());
            DataGridCollection.Filter = new Predicate<object>(Filter);

            pixsellOrders.ColumnChanged += new DataColumnChangeEventHandler(Column_Changed);

        }
        catch (SqlException sqlEr)
        {
            Console.WriteLine(sqlEr);
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
            _dataGridCollection.Refresh();
        }
    }

    public DataTable SqlConnect(string query)
    {
        SqlConnection ohsql1;
        string sqlQuery = query;

        ohsql1 = new SqlConnection("Data Source=OHSQL1;Initial Catalog=Reporting;Integrated Security = true");


        DataTable table = new DataTable();

        try
        {
            //connect
            ohsql1.Open();

            //fill datatable with results
            SqlDataAdapter a = new SqlDataAdapter(sqlQuery, ohsql1);

            //fill table
            a.Fill(table);

            //kill connection
            a.Dispose();
            ohsql1.Close();

        }
        catch (SqlException e)
        {
            Console.WriteLine("SQL ERROR: " + e);
        }

        return table;
    }

    private void MenuItem_Click(object sender, RoutedEventArgs e)
    {
        _filterString = FilterBox.Text;

        if (_filterString == "")
        {
            Console.WriteLine("no filter");
            return;
        }
        else
        {
            Console.WriteLine(_filterString);
            FilterCollection();
        }
    }

    private void FilterCollection()
    {
        if (_dataGridCollection != null)
        {
            _dataGridCollection.Refresh();
        }
    }

    private bool Filter(object obj)
    {
        if (obj is DataRow data)
        {
            if (!string.IsNullOrEmpty(_filterString))
            {
                return data["CUNAME"].ToString().Contains(_filterString);
            }
            else
            {
                return true;
            }

        }
        return false;
    }

指定的“CUNAME”列只是一个测试,最终我想让它知道过滤器按钮被按下的列。

我遇到的问题是 DataGrid 返回为空。当我执行 Grid.ItemsSource = pixsellOrders.DefaultView (或类似的东西,不记得确切的语法)时,它可以正常工作并填充网格。

我已尝试更改为肯定是 IEnumerable 的列表,但它也没有填充数据网格。添加 AutoGenerateColumns(true 或 false)无效。输出中没有显示错误。注释掉所有过滤器部分也没有效果。删除上下文菜单也没有效果。删除 AsEnumerable() 对网格填充没有影响,但会在 DataGridCollection.Filter 处抛出错误。

谁能看出这是哪里出了问题?如果您能建议我如何检查列名(而不是对所有列进行硬编码),我们也会很有帮助)

提前谢谢你

【问题讨论】:

  • 抓得好!但不幸的是不是问题(我在尝试不添加绑定后拼错了)

标签: c# wpf xaml datagrid


【解决方案1】:

WindowDataContext设置为自身:

public PixsellOrders(string windowTitle)
{
    InitializeComponent();
    DataContext = this;

    //...
}

【讨论】:

  • 这肯定会增加我的网格!然而 AsEnumerable 将废话传递给网格,但删除它会在 DataGridCollection.Filter = new Predicate(Filter); 处引发“不支持指定方法”
  • 如果您有新问题,请提出新问题。您最初的问题是关于绑定和空的 DataGrid。
  • 您不能使用 CollectionView 过滤 DataTable。不支持:stackoverflow.com/questions/9385489/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-12
相关资源
最近更新 更多