c# - 有什么办法可以在 x :DataType? 中使用值类型

标签 c# xaml windows-store-apps uwp

鉴于此 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 运算符的 View 自动生成的代码。

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 中绑定(bind) 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>

关于c# - 有什么办法可以在 x :DataType? 中使用值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32880138/

相关文章:

C# 设计选择——COM 对象还是另一个类?

xaml - 弹出窗口中应用栏按钮的单击事件在 UWP 中不起作用

c# - 如何停止消息中心在 Xamarin.Forms 中多次停止订阅?

c# - nhibernate queryOver 投影语法

c# - 如何获取发布版本?

c# - 列表框 WP7 中的反向堆栈项目

c# - 如何设置文本框标题的样式?

wpf - 如何禁用 AutoSuggestBox 上的拼写检查器

c# - 嵌套 ListView 中的 SelectedItems

c# - 字符串或二进制数据将被截断。?