在x:DataType中是否有任何方式可以使用值类型?

9
考虑到这个 DataTemplate
<DataTemplate x:DataType="Color">
    ...
</DataTemplate>

我得到了以下错误:

必须使用as运算符与引用类型或可空类型一起使用('Color'是一个非可空值类型)

当你跟随这个错误时,它会带你去查看自动生成的视图代码,该代码使用了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}是比较新的技术,但是有没有人知道如何配置它以允许值类型,或者至少使用直接转换?

2个回答

5

当在x:DataType中绑定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>

1
我本来希望不用这么做,但看来这是唯一的办法了。谢谢 Jeffrey。 - Laith

2
@JeffreyChen的解决方案绝对正确,适用于任何其他值类型。但在这种特定情况下,引用类型的SolidColorBrush公开了Color属性,这是系统已经为您构建好的。
我建议将VM中的Color属性更改为SolidColorBrush,因为只有在您想要两个状态之间的平滑ColorAnimation时才需要在xaml中使用Color。 如果是这种情况,您可以执行-
<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类型。
<ListView ItemsSource="{x:Bind Vm.Brushes}">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="SolidColorBrush">
            <TextBlock Text="Test" Foreground="{x:Bind}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

在这种情况下,是的,“SolidColorBrush”解决了问题。但是,我使用“Color”作为值类型的示例。我可能会从可移植库中获取值类型,其中VM位于其中,甚至使用原始类型,例如“int []”,其中“<DataTemplate x:DataType =”x:Int32">”。 - Laith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接