在单元格值中绑定WPF DataGrid列标题文本
本文关键字:DataGrid 标题 文本 WPF 绑定 单元格 | 更新日期: 2023-09-27 17:57:37
我有一个DataGrid,我希望在Cell 中的每个值中附加列标题文本
XAML源代码是
<Window x:Class="DataGrid_Index.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:cust="clr-namespace:DataGrid_Index" >
<Grid>
<DataGrid Name="Grid1" AutoGenerateColumns="False" ItemsSource="{Binding MobileList, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="True" SelectionUnit="Cell" SelectionChanged="Grid1_SelectionChanged" >
<DataGrid.Columns>
<!--Column 1-->
<DataGridTextColumn Binding="{Binding MobileName}" Header="Name" />
<!--Column 2-->
<DataGridTextColumn Binding="{Binding MobileOS}" Header="OS" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
C#视图模型是
public class MobileVM : ViewModel
{
private ObservableCollection<Mobile> _mobileList = new ObservableCollection<Mobile>();
public ObservableCollection<Mobile> MobileList
{
get { return _mobileList; }
set { _mobileList = value; OnPropertyChanged(); }
}
public MobileVM()
{
MobileList = new ObservableCollection<Mobile>()
{
new Mobile() { MobileName = "iPhone 6", MobileOS = "IOS" },
new Mobile() { MobileName = "Galaxy S6", MobileOS = "Android" },
new Mobile() { MobileName = "Lumina", MobileOS = "Windows" }
};
}
}
public class Mobile
{
public string MobileName { get; set; }
public string MobileOS { get; set; }
}
我期待输出
Name OS
_________________________________________
Name: iPhone 6 OS: IOS
Name: Galaxy S6 OS: Android
Name: Lumina OS: Windows
如何在细胞中结合Column.Header
?请协助我。
您可以使用这样的MultiBinding:来实现这一点
<DataGridTextColumn Header="Name" x:Name="NameC">
<DataGridTextColumn.Binding>
<MultiBinding StringFormat=" {0}: {1}">
<Binding ElementName="NameC" Path="Header"></Binding>
<Binding Path="MobileName"></Binding>
</MultiBinding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
StringFormat
允许您进行更多的自定义。
希望这能帮助