问题
I have a GridView where I can generate the Columns at run time based upon the configuration settings. e.g Text Column = to show the text in it Image Column = to display the graphic in there.
but the problem is that the whole column would be shown either of them type. What I want to do is based upon the data of particular cell, I want (a) choose a dynamic template (b) render the contents dynamically (ideally) as FrameworkElement and set the cell content with that.
This means that the each cell can either display text or image. so in first row, 1st column could be text and 2nd row, 1st column could be graphics based upon the data value.
Is there a way to choose the template based upon run time content value of particular cell or completely render a UIElement and then set as value of the cell?
Example:-
Cell data = <bold>Hello. I'm bold</bold>
=> displays the text as bold (TextBlock Element)
Cell data = <img>test.png</img>
=> displays the graphic (Image Element)
回答1:
You can achieve this with Triggers
Here is the sample code. .
<ListView Margin="10" Name="lvUsers">
<ListView.View>
<GridView x:Name="gridview">
<GridViewColumn Header="Type">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ContentControl>
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsImage}" Value="True">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Text="Text goes here"
Foreground="Red"/>
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding IsImage}" Value="False">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Text="Image goes here"/>
<!--<Image Source="{Binding source}" />-->
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
And the sample backend code
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<myClass> mc = new List<myClass>();
mc.Add(new myClass() { Itemsource = "textblock text", IsImage = false });
mc.Add(new myClass() { Itemsource = "Image source", IsImage = true });
lvUsers.ItemsSource = mc;
}
}
class myClass
{
public string Itemsource { get; set; }
public bool IsImage { get; set; }
}
来源:https://stackoverflow.com/questions/35577870/wpf-gridview-column-and-dynamic-cell-template-based-upon-data-value