[英]How to get WPF DataGrid to use member variables of classes in DataGridTextColumn?
I am trying to bind a DataGrid.ItemSource
to a ObservableCollection<SearchObject>
. 我正在尝试将
DataGrid.ItemSource
绑定到ObservableCollection<SearchObject>
。 SearchObject is a custom class which has some public member variables (one is named "parameters"). SearchObject是一个自定义类,具有一些公共成员变量(一个名为“ parameters”)。 Parameters is a custom class and has a public member variable (of type string) named "query".
参数是一个自定义类,并具有一个名为“查询”的公共成员变量(类型为字符串)。 How can I get the "query" string to show up in the datagrid.
如何获取“查询”字符串以显示在数据网格中。
I tried Binding="{Binding ElementName=parameters, Path=query}"
within a DataGridTextColumn
, but it didn't seem to work. 我在
DataGridTextColumn
尝试了Binding="{Binding ElementName=parameters, Path=query}"
,但它似乎没有用。 I imagined this would reference the parameters object and then look for its query member variable, but this didn't seem to work. 我以为这会引用参数对象,然后查找其查询成员变量,但这似乎不起作用。
Any ideas? 有任何想法吗? Here is my XAML:
这是我的XAML:
<DataGrid HorizontalAlignment="Stretch" Name="watchListDataGrid"
VerticalAlignment="Stretch" IsReadOnly="True"
AlternatingRowBackground="#FFE4F0FC"
HorizontalScrollBarVisibility="Disabled"
SelectionChanged="watchListDataGrid_SelectionChanged"
CanUserReorderColumns="False"
CanUserSortColumns="False"
AutoGenerateColumns="False" KeyUp="watchListDataGrid_KeyUp">
<DataGrid.ContextMenu>
<ContextMenu >
<MenuItem Header="Remove" Click="MenuRemoveWatchListItem_Click" />
</ContextMenu>
</DataGrid.ContextMenu>
<DataGrid.Columns>
<DataGridTextColumn Header="Query" Width="*"
Binding="{Binding ElementName=parameters, Path=query}" />
</DataGrid.Columns>
Assuming your DataGrid's ItemsSource is bound to something like: 假设您的DataGrid的ItemsSource绑定到以下内容:
<DataGrid ItemsSource={Binding Path=parameters}>
The DataGridTextColumn's Binding should be: DataGridTextColumn的绑定应为:
<DataGridTextColumn Binding="{Binding Path=query}" />
You use ElementName to reference another element within your XAML. 您可以使用ElementName引用XAML中的另一个元素。 For example, if you wanted to bind the text of a TextBlock to the text of a TextBox:
例如,如果您想将TextBlock的文本绑定到TextBox的文本:
<TextBox Name="myTextBox" />
<TextBlock Text={Binding Path=Text, ElementName=myTextBox} />
I was able to resolve the problem. 我能够解决问题。 Yazan, your suggestion to use this code DID work:
Yazan,您对使用此代码DID的建议:
<DataGridTextColumn Binding="{Binding Path=query}" />
However, I was missing { get; 但是,我很想念{ set;
组; } for the SearchObject's "parameters" member variable.
}用于SearchObject的“参数”成员变量。 When I added these, it all worked fine:
当我添加这些时,一切正常:
public class SearchObject : ISerializable
{
public SearchParameters parameters { get; set; }
Thanks again for your help! 再次感谢你的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.