【发布时间】:2017-07-20 19:15:33
【问题描述】:
我正在尝试绑定到下面DataGrid 中的StringValue 对象集合。但是每个项目都显示在单独的行中。
我希望它具有柱状显示。例如,值 565477 和 65656 应显示在一行中。
XAML:
<TreeView>
<TreeViewItem Header="Warnings">
<TreeView ItemsSource="{Binding WarningCategories}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Warnings}">
<TextBlock Text="{Binding Path=Category}" />
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<DataGrid ItemsSource="{Binding Fields}" AutoGenerateColumns="True" HeadersVisibility="None">
</DataGrid>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</TreeViewItem>
</TreeView>
代码隐藏:
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<WarningCategory> WarningCategories { get; set; }
public ViewModel()
{
WarningCategories = new ObservableCollection<WarningCategory>();
ObservableCollection<Warning> warnings = new ObservableCollection<Warning>
{
new Warning( new StringValue("565477"), new StringValue("65656")),
new Warning( new StringValue("767455"), new StringValue("75642")),
};
WarningCategories.Add(new WarningCategory("Warning One", warnings));
warnings = new ObservableCollection<Warning>
{
new Warning( new StringValue("565477"), new StringValue("65656")),
new Warning( new StringValue("767455"), new StringValue("75642")),
};
WarningCategories.Add(new WarningCategory("Warning Two", warnings));
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public class WarningCategory
{
public string Category { get; set; }
private ObservableCollection<Warning> m_warnings;
public ObservableCollection<Warning> Warnings
{
get
{
return m_warnings ?? (m_warnings = new ObservableCollection<Warning>());
}
}
public WarningCategory(string category, ObservableCollection<Warning> animals)
{
Category = category;
m_warnings = animals;
}
}
public class Warning
{
public ObservableCollection<StringValue> Fields { get; set; }
public Warning(params StringValue[] fields)
{
Fields = new ObservableCollection<StringValue>(fields);
}
}
public class StringValue
{
public StringValue(string s)
{
Value = s;
}
public string Value { get; set; }
}
我希望最终结果是这样的:
到目前为止我的解决方法,但不幸的是它不支持多选!
<ItemsControl ItemsSource="{Binding Fields}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Value}" Width="150"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
【问题讨论】:
-
您真的想在数据网格中拥有多行吗?为什么要使用数据网格?
-
@DanField 实际上没有。但我希望能够选择整行。我在 DataGrid 中发现了这种功能-
-
您能否在帖子中添加一些内容,显示您期望的最终输出结果?
-
@DanField 我添加了。
-
我不是 100% 清楚您现在想要多选的内容 - 单个值?行?两者都有?
标签: c# wpf xaml datagrid treeview