将字典数据绑定到WPF数据网格



我目前有一个WPF,它接收一个字符串,对其进行解析,并将其存储在字典中,其中键将是列标题,值将在其下。解析字符串后,第二个WPF弹出窗口将打开,其中包含一个数据网格,应显示此解析消息。我浏览了Stack Overflow,了解了其他有这个问题的人,但他们的解决方案都不适用于我。

主窗口


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();
}

弹出窗口

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>

您忘记设置绑定的源对象:

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

或者,设置

DataContext = this;

在Window的构造函数中。

最新更新