Home > database >  Binding Dictionary Data to WPF Data Grid
Binding Dictionary Data to WPF Data Grid

Time:10-18

I currently have a WPF that takes in a string, parses it and stores it in a dictionary where the key would be the column header, and value would be under it. Once the string is parsed a SECOND WPF Pop up opens with a Data Grid that should display this parsed message. I have looked through Stack Overflow to see others who have had this issue but none of their solutions have worked for mine.

MainWindow



public MainWindow()
        {
            
            InitializeComponent();
            DataContext = this;
        }

        
private void Button_Click(object sender, RoutedEventArgs e)
        {
            string input = HelloTextBox.Text;

            IMessage message = parseMessage(input);

            Type messageType = message.GetType();

            PropertyList proplist = GetPropertyList(messageType, message);

            // display message properties in popup window
            InfoDialog infoPopUp = new(proplist);
            infoPopUp.ShowDialog();

        }

Popup Window

public partial class InfoDialog : Window
{
    
    public PropertyList PropertyList { get; set; }
    public InfoDialog(PropertyList propList)
    {
        InitializeComponent();
        this.PropertyList = propList;
        
    }

XAML

<Grid>
    ItemsSource="{Binding PropertyList,
          RelativeSource={RelativeSource AncestorType=Window}}" AutoGenerateColumns="False" SelectionChanged="DataGridXAML_SelectionChanged">
        <DataGrid.Columns>
            <!-- Header Text and Bindings -->
            <DataGridTextColumn Header="Key" Binding="{Binding Key}" Width="*"/>
            <DataGridTextColumn Header="Value" Binding="{Binding Value}"  Width="*"/>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

CodePudding user response:

You forgot to set the source object of the Binding:

ItemsSource="{Binding PropertyList,
              RelativeSource={RelativeSource AncestorType=Window}}"

Alternatively, set

DataContext = this;

in the Window's constructor.

  • Related