I'm using a key/value observable collection to hold data which is represented in the view by a two column datagrid. Some key values contain a list of items and other key values contain a single string value. Using the below code snippet I'm able to display those key values with items in a combobox. However, the key value 'string' rows display no information and the row becomes read-only. I'm trying not to use code behind. What am I doing wrong? Would it be simple to solve with code behind and if so, what's the best approach?
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding KeyValuesCollection}" HorizontalAlignment="Left" Margin="10,10,10,10">
<DataGrid.Columns>
<DataGridTextColumn Header="Field" Binding="{Binding Description}" Width="320"/>
<DataGridTemplateColumn Header="Value" Width="330">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Path=ValueItems}"
Visibility="{Binding ComboVisible,
Converter={StaticResource BoolToVis}}"
DisplayMemberPath="ValueName"
SelectedValuePath="ID"
SelectedValue="{Binding Id}"
/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Here is the structure of the items:
public class KeyValue : PropertyChangedBase
{
public string Description { get; set; }
public List<ValueItem> ValueItems { get; set; }
public bool ComboVisible = false;
}
ValueItems is a list of id, string.
Try using a DataTrigger with predefined DataTemplate items:
<DataTemplate x:Key="OneItem" DataType="{x:Type ValueItem}" >
<TextBox Text="{TemplateBinding Id}" />
</DataTemplate>
<DataTemplate x:Key="MultiItems" DataType="{x:Type ValueItem}" >
<ComboBox ItemsSource="{TemplateBinding ValueItems}"
DisplayMemberPath="ValueName"
SelectedValuePath="ID"
SelectedValue="{TemplateBinding Id}" />
</DataTemplate>
And then use a Content control to place the style accordingly. I haven't tried this but your data items could easily have a "HasMultipleValueItems" boolean flag for an easy binding.
<DataGridTemplateColumn Header="Value" Width="330">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ContentControl Content="{Binding}">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="ContentTemplate" Value="{StaticResource OneItem}" />
<Style.Triggers>
<DataTrigger Binding="{Binding HasMultipleValueItems}" Value="True">
<Setter Property="ContentTemplate" Value="{StaticResource MultiItems}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.