有什么方法可以在 x:DataType 中使用值类型?

Is there any way I can use value types in x:DataType?

鉴于此 DataTemplate:

<DataTemplate x:DataType="Color">
    ...
</DataTemplate>

我收到以下错误:

The as operator must be used with a reference type or nullable type ('Color' is a non-nullable value type)

当您按照错误进行操作时,它会将您带到为使用 as 运算符的视图自动生成的代码。

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();
}

我知道 {x:Bind} 是新的,但以防万一,有谁知道如何配置它以允许值类型,或者至少使用直接转换?

我在 x:DateType 中绑定 Windows 运行时类型如“Windows.UI.Color”时遇到同样的问题。

我目前使用的解决方法是包装 .NET 引用类型。

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 的解决方案绝对正确,可以应用于任何其他值类型。但是在这个特定的例子中,一个类型为 SolidColorBrush 的引用公开了 Color 的 属性 是系统已经为你构建的东西。

我建议将您的 VM 中的 Color 属性 更改为 SolidColorBrush 因为只有在您的 [=28= 中需要 Color ] 是当你想要在两个状态之间平滑 ColorAnimation 时。如果是这种情况你做 -

<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>

否则,您只需绑定到 XAML 控件的 Foreground/Background/BorderBrush,它已经是 Brush.[=22= 的一种类型]

<ListView ItemsSource="{x:Bind Vm.Brushes}">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="SolidColorBrush">
            <TextBlock Text="Test" Foreground="{x:Bind}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>