Reputation: 115
Following the response on this windows-toolkit issue, I'm using x:Bind to bind elements of an ObservableCollection of AlertEntry's to DataGridColumn cells. My XAML is as follows:
<controls:DataGrid ItemsSource="{x:Bind ViewModel.Alerts, Mode=OneWay}" AutoGenerateColumns="True" IsReadOnly="True">
<controls:DataGrid.Columns>
<controls:DataGridTemplateColumn Header="Time" >
<controls:DataGridTemplateColumn.CellTemplate>
<DataTemplate x:DataType="ace:AlertEntry">
<TextBlock Text="{x:Bind Timestamp, Converter={StaticResource StringFormatConverter}, ConverterParameter='{}{H:mm:ss}'}"/>
</DataTemplate>
</controls:DataGridTemplateColumn.CellTemplate>
</controls:DataGridTemplateColumn>
</controls:DataGrid.Columns>
</controls:DataGrid>
And my AlertEntry class:
public class AlertEntry
{
public DateTime Timestamp;
public ACEEnums.AlertLevel Level;
public ACEEnums.AlertType Type;
public string Info;
public AlertEntry(ACEEnums.AlertLevel level, ACEEnums.AlertType type, string info = "")
{
Timestamp = DateTime.Now;
Level = level;
Type = type;
Info = info;
}
}
When elements are added to ViewModel.Alerts I can see highlightable rows are added to the DataGrid, but they display no content. When I remove the binding and add a fixed text value, it displays that value correctly every time a row is added.
The AlertEntry items in ViewModel.Alerts correctly contain data.
I've confirmed the StringFormatConverter works in other bindings. In fact the StringFormatConverter is not ever being called.
I'm using MVVM-Light and UWP.
Thank you!
Upvotes: 0
Views: 261
Reputation: 115
My DataGrid is an element of a StackPanel and I was declaring my converters as static resources of the StackPanel like so:
<StackPanel.Resources>
<helper:StringFormatConverter x:Key="StringFormatConverter" />
<helper:AlertToString x:Key="AlertToString" />
</StackPanel.Resources>
I moved the converters to be resources of the whole page instead, and at that point they started working.
<Page.Resources>
<helper:StringFormatConverter x:Key="StringFormatConverter" />
<helper:AlertToString x:Key="AlertToString" />
</Page.Resources>
Upvotes: 0
Reputation: 32775
For the testing, the problem may occur in your StringFormatConverter
, TextBlock
Text property only allow string value, So we need return string type value in Convert
method.
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null)
return null;
if (parameter == null)
return value;
var dt = (DateTime)value;
return dt.ToString((string)parameter);
}
And x:Bind support bind function , you could try use Text="{x:Bind Timestamp.ToString()}"
to verify above.
Upvotes: 1