在我们的WPF应用程序中,我们有一个显示网格的屏幕,现在列的标题是文本,我应该在文本旁边添加图像。这是XAML代码,
<Custom:DataGrid.Columns>
<Custom:DataGridTemplateColumn Header="{Binding EmailIDHeader, Source={StaticResource LiteralDictionary}}" Width = "0.1*" CellTemplate="{StaticResource EmailIDTemplate}" SortMemberPath="EmailID"/>
</Custom:DataGrid.Columns>
<DataTemplate x:Key="EmailIDTemplate">
<Grid MinWidth="10" Margin="5,0,5,0">
<TextBlock HorizontalAlignment="Left" Text="{Binding customerItem.EmailID}" Margin="0,0,3,0"/>
</Grid>
EMailIDHeader将加载Header的Text值,我必须在它旁边添加一个图像。我该如何实现这一目标?我尝试了here给出的解决方案。但这只是向我显示一个空标题列。
答案 0 :(得分:0)
定义DataTemplate
,根据需要整理文本块和图片,并使用此资源设置属性HeaderTemplate
。
标题的数据模板:
<DataTemplate x:Key="EmailIDHeaderTemplate">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Image Source="SPhotoEditor-20170120_075433.jpg" Width="20" Height="20"></Image>
<TextBlock HorizontalAlignment="Left" Text="{Binding EmailIDHeader, Source={StaticResource LiteralDictionary}}" Margin="0,0,3,0"/>
</Grid>
</DataTemplate>
对于细胞:
<DataTemplate x:Key="EmailIDTemplate">
<Grid MinWidth="10" Margin="5,0,5,0">
<TextBlock HorizontalAlignment="Left" Text="{Binding customerItem.EmailID}" Margin="0,0,3,0"/>
</Grid>
</DataTemplate>
你的网格:
<Custom:DataGrid.Columns>
<Custom:DataGridTemplateColumn HeaderTemplate="{StaticResource EmailIDHeaderTemplate}" CellTemplate="{StaticResource EmailIDTemplate}" Width = "0.1*" SortMemberPath="EmailID"/>
</Custom:DataGrid.Columns>
答案 1 :(得分:0)
假设模型是
public class Model : INotifyPropertyChanged
{
string _value;
public string Value{ get { return _value; } set { _value = value; RaisePropertyChanged("Value"); } }
public event PropertyChangedEventHandler PropertyChanged;
void RaisePropertyChanged(string propname)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propname));
}
}
并且视图模型中有两个属性:
string _name;
public string Name { get { return _name; } set { _name = value; RaisePropertyChanged("Name"); } }
string _imagePath;
public string ImagePath { get { return _imagePath; } set { _imagePath = value; RaisePropertyChanged("ImagePath"); } }
您可以使用以下视图:
<DataGrid DataContext="{Binding}" ItemsSource="{Binding Models}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.Name}"/>
<Image Source="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.ImagePath}"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Value}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>