【问题标题】:Is there any way I can use value types in x:DataType?有什么方法可以在 x:DataType 中使用值类型?
【发布时间】:2015-12-29 01:38:32
【问题描述】:

鉴于此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} 是新的,但以防万一,有谁知道如何配置它以允许值类型,或者至少使用直接转换?

【问题讨论】:

    标签: c# xaml windows-store-apps uwp


    【解决方案1】:

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

    【讨论】:

    • 我希望我不必这样做,但我想这是唯一的方法。谢谢杰弗里。
    【解决方案2】:

    @JeffreyChen 的解决方案绝对正确,可以应用于任何其他值类型。但是在这个特定的例子中,类型为 SolidColorBrush 的引用公开了 Color 的属性,这是系统已经为您构建的。

    我建议将您的 VM 中的 Color 属性更改为 SolidColorBrush,因为您唯一需要在 xaml 中使用 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 的一种类型。

    <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[] where &lt;DataTemplate x:DataType="x:Int32"&gt;
    猜你喜欢
    • 2021-05-22
    • 1970-01-01
    • 2014-05-15
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多