C#WPF DataGrid绑定IEnumerable <someclass>

时间:2018-12-21 10:01:35

标签: c# wpf datagrid

我想在WPF MVVM中做一些DataGrid。我是新来的。

为什么我的简单解决方案不起作用?

我要绑定此:

public IEnumerable<ZenonClasses.RGMRecipeValue> Values
        {
            get => SelectedPhase?.ValueItems;
        }

对此:

        <DataGrid ItemsSource="{Binding Values.VarName}" HorizontalAlignment="Left" Height="171" Margin="10,0,0,0" Grid.Row="4" Grid.RowSpan="5" VerticalAlignment="Top" Width="380" Grid.ColumnSpan="2"/>

但是我的DataGrid是空的。 我想我需要一些配置,并且我正在寻找简单的解决方案,很遗憾,没有找到足以为我解释的内容。

1 个答案:

答案 0 :(得分:0)

首先,我将假定您的窗口(xaml)具有datacontext,它是Model View类,用于实现您要提及的属性(值)。 如果没有,那么您必须确保发生这种情况。我通常要做的是在后面的窗口代码上分配它:

    public MainWindow()
    {
        InitializeComponent();
        vm = new YOURVIEWMODELCLASS();
        DataContext = vm;
    }

然后,您的DataGrid控件需要有一个colums的定义,我在您的代码示例中没有看到此定义,但是您需要提供它们,因此该控件知道要“绘制”多少列,这在此处进行了说明详细信息:

https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.datagrid?view=netframework-4.7.2

然后是“值”属性本身。您当前的类型是IEnumerable,您可能需要将此类型更改为ObservableCollection,因为这更适合WPF中的数据绑定。

最后,请确保您的ModelView类实现了INotifyPopertyChanged接口,因为WPF提供了该机制以使数据绑定有效地工作。这是我的一个应用程序中的示例代码:

public class MainWindowViewModel : INotifyPropertyChanged
{
 private ObservableCollection<Results> searchResults;

 public ObservableCollection<Results> SearchResults { get => searchResults; set { searchResults = value; NotifyPropertyChanged(); } }


#region INotifyPropertyChanged

public event PropertyChangedEventHandler PropertyChanged;

protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

#endregion

//Other code here.... 

}

在这种情况下,我的属性SearchResults使用如下所示的DataGrid在窗口中显示:

<DataGrid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" Grid.RowSpan="3" Margin="10" ItemsSource="{Binding SearchResults}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Term" Binding="{Binding SearchedTopic}"/>
            <DataGridTextColumn Header="Match Count" Binding="{Binding FoundPaths.Count}" />
        </DataGrid.Columns>
        <DataGrid.RowDetailsTemplate>
            <DataTemplate>
                <DataGrid Margin="5" ItemsSource="{Binding FoundPaths}" AutoGenerateColumns="False">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="Found" Binding="{Binding}"/>
                    </DataGrid.Columns>
                </DataGrid>
            </DataTemplate>
        </DataGrid.RowDetailsTemplate>
    </DataGrid>

希望这会有所帮助。

相关问题