Is there a way to use value types in x: DataType?
Given this DataTemplate :
<DataTemplate x:DataType="Color"> ... </DataTemplate> I get the following error:
The as operator must be used with a reference type or a type with a null value ("Color" is a value type that is not nullable)
When you execute this error, you will get automatically generated code for this view, which uses the as operator.
public void DataContextChangedHandler(global::Windows.UI.Xaml.FrameworkElement sender, global::Windows.UI.Xaml.DataContextChangedEventArgs args) { global::Windows.UI.Color data = args.NewValue as global::Windows.UI.Color; if (args.NewValue != null && data == null) { throw new global::System.ArgumentException("Incorrect type passed into template. Based on the x:DataType global::Windows.UI.Color was expected."); } this.SetDataRoot(data); this.Update(); } I know that {x:Bind} is new, but just in case, does anyone know how to configure it to allow value types, or at least use direct casting?
I have the same problem when binding a Windows Runtime type as "Windows.UI.Color" in x: DateType.
The current workaround I used is porting the .NET Reference Type.
public class BindModel { public Windows.UI.Color Color { get; set; } } <DataTemplate x:Key="test" x:DataType="local:BindModel"> <TextBlock> <TextBlock.Foreground> <SolidColorBrush Color="{x:Bind Color}"></SolidColorBrush> </TextBlock.Foreground> </TextBlock> </DataTemplate> @JeffreyChen is absolutely correct and can be applied to any other type of value. But in this particular case, the link printed by SolidColorBrush that provides the Color property is what the system has already built for you.
I would suggest changing the Color property on your virtual machine to SolidColorBrush , because you will need Color when you only need Color in your xaml, when you want to smooth the ColorAnimation between two states. If so, you do -
<ListView ItemsSource="{x:Bind Vm.Brushes}"> <ListView.ItemTemplate> <DataTemplate x:DataType="SolidColorBrush"> <TextBlock Text="Test"> <TextBlock.Foreground> <SolidColorBrush Color="{x:Bind Color}" /> </TextBlock.Foreground> </TextBlock> </DataTemplate> </ListView.ItemTemplate> </ListView> Otherwise, you simply snap to the XAML Foreground / Background / BorderBrush , which is already a Brush type.
<ListView ItemsSource="{x:Bind Vm.Brushes}"> <ListView.ItemTemplate> <DataTemplate x:DataType="SolidColorBrush"> <TextBlock Text="Test" Foreground="{x:Bind}" /> </DataTemplate> </ListView.ItemTemplate> </ListView>