c#-使用x:Bind使用Converter绑定到当前DataContext

我有以下转换器:

public class MyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
         Debug.WriteLine(value.GetType());             

         //The rest of the code             
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

以及尝试使用转换器的XAML:

<ListView ItemsSource="{x:Bind StickersCVS.View}" >
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="models:StickerCategory">
            <TextBlock Foreground="{x:Bind Converter={StaticResource MyConverter}}"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

这给了我一个value.GetType()的NPE,显然传入的值是null.

如果我更改以下部分:

< TextBlock Foreground =“ {x:Bind Converter = {StaticResource MyConverter}}” />

< TextBlock Foreground =“ {Binding Converter = {StaticResource MyConverter}}” />

然后就可以了.调试正确输出StickerCategory作为值的类型. x:Bind将null传递到转换器的任何原因以及如何使其与x:Bind一起使用?我正在尝试将DataContext传递给我的转换器.

解决方法:

{x:Bind}使用生成的代码来实现其优势,并且在{x:Bind}中使用不同的Path时,生成的代码具有一些差异.

在这里,我使用一个简单的示例.对于完整的样本,请检查GitHub.

在示例中,我有一个如下的ViewModel:

public class MyViewModel
{
    public MyViewModel()
    {
        MyList = new List<Item>()
        {
            new Item {Name="1",Number=1 },
            new Item {Name="2",Number=2 },
            new Item {Name="3",Number=3 }
        };
    }

    public List<Item> MyList { get; set; }
}

public class Item
{
    public string Name { get; set; }
    public int Number { get; set; }

    public override string ToString()
    {
        return string.Format("Name: {0}, Number {1}", this.Name, this.Number);
    }
}

当我们在MainPage.xaml中使用{x:绑定名称时,Converter = {StaticResource ItemConvert}}

<ListView ItemsSource="{x:Bind ViewModel.MyList}">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="local:Item">
            <TextBlock Text="{x:Bind Converter={StaticResource ItemConvert}}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

它在MainPage.g.cs中生成以下代码

public void DataContextChangedHandler(global::Windows.UI.Xaml.FrameworkElement sender, global::Windows.UI.Xaml.DataContextChangedEventArgs args)
{
     global::xBindWithConverter.Item data = args.NewValue as global::xBindWithConverter.Item;
     if (args.NewValue != null && data == null)
     {
        throw new global::System.ArgumentException("Incorrect type passed into template. Based on the x:DataType global::xBindWithConverter.Item was expected.");
     }
     this.SetDataRoot(data);
     this.Update();
}

// IDataTemplateExtension

public bool ProcessBinding(uint phase)
{
    throw new global::System.NotImplementedException();
}

public int ProcessBindings(global::Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs args)
{
    int nextPhase = -1;
    switch(args.Phase)
    {
        case 0:
            nextPhase = -1;
            this.SetDataRoot(args.Item as global::xBindWithConverter.Item);
            if (!removedDataContextHandler)
            {
                removedDataContextHandler = true;
                ((global::Windows.UI.Xaml.Controls.TextBlock)args.ItemContainer.ContentTemplateRoot).DataContextChanged -= this.DataContextChangedHandler;
            }
            this.initialized = true;
            break;
    }
    this.Update_((global::xBindWithConverter.Item) args.Item, 1 << (int)args.Phase);
    return nextPhase;
}
...
public void Update()
{
    this.Update_(this.dataRoot, NOT_PHASED);
    this.initialized = true;
}

global::Windows.UI.Xaml.Controls.TextBlock element3 = (global::Windows.UI.Xaml.Controls.TextBlock)target;
MainPage_obj3_Bindings bindings = new MainPage_obj3_Bindings();
returnValue = bindings;
bindings.SetDataRoot((global::xBindWithConverter.Item) element3.DataContext);
bindings.SetConverterLookupRoot(this);
element3.DataContextChanged += bindings.DataContextChangedHandler;
global::Windows.UI.Xaml.DataTemplate.SetExtensionInstance(element3, bindings);

初始化Page时,element3.DataContextChanged = bindings.DataContextChangedHandler;将首先执行.此后,将在初始化时引发DataContextChanged事件,从而调用DataContextChangedHandler方法.然后将执行ProcessBindings方法,以使用绑定数据更新列表项容器元素.

在DataContextChangedHandler方法中,它调用this.Update();.最后调用Update_(global :: xBindWithConverter.Item obj,int phase)方法的方法.但是,当调用DataContextChangedHandler方法时,它的args.NewValue值为null,因此Update_(global :: xBindWithConverter.Item obj,int阶段)方法中的obj也为null.

并且在XAML中使用{x:Bind Converter = {StaticResource ItemConvert}}时,Update_(global :: xBindWithConverter.Item obj,int阶段)的生成代码为:

// Update methods for each path node used in binding steps.
private void Update_(global::xBindWithConverter.Item obj, int phase)
{
    if((phase & ((1 << 0) | NOT_PHASED )) != 0)
    {
        XamlBindingSetters.Set_Windows_UI_Xaml_Controls_TextBlock_Text(this.obj3.Target as global::Windows.UI.Xaml.Controls.TextBlock, (global::System.String)this.LookupConverter("ItemConvert").Convert(obj, typeof(global::System.String), null, null), null);
    }
}

由于obj为null,因此Convert中的值为null,最后它将在value.GetType()处抛出NPE.

但是,如果我们在{x:Bind}中使用另一个路径,例如{x:Bind Name,Converter = {StaticResource ItemConvert}},则Update_(global :: xBindWithConverter.Item obj,int阶段)的生成代码是不同的:

// Update methods for each path node used in binding steps.
private void Update_(global::xBindWithConverter.Item obj, int phase)
{
    if (obj != null)
    {
        if ((phase & (NOT_PHASED | (1 << 0))) != 0)
        {
            this.Update_Name(obj.Name, phase);
        }
    }
}
private void Update_Name(global::System.String obj, int phase)
{
    if((phase & ((1 << 0) | NOT_PHASED )) != 0)
    {
        XamlBindingSetters.Set_Windows_UI_Xaml_Controls_TextBlock_Text(this.obj3.Target as global::Windows.UI.Xaml.Controls.TextBlock, (global::System.String)this.LookupConverter("ItemConvert").Convert(obj, typeof(global::System.String), null, null), null);
    }
}

它将确定obj是否为null.因此,此处不会调用XamlBindingSetters.Set_Windows_UI_Xaml_Controls_TextBlock_Text方法,并且不会发生NullReferenceException.

要解决此问题,就像@MarkusHütter所说的那样,您可以在转换器中添加一个空检查,例如:

public object Convert(object value, Type targetType, object parameter, string language)
{
    if (value != null)
    {
        System.Diagnostics.Debug.WriteLine(value.GetType());
        return value.ToString();
    }
    else
    {
        System.Diagnostics.Debug.WriteLine("value is null");
        return null;
    }
}
上一篇:C#-ContentDialog在外部点击时关闭


下一篇:c#-无法引用UWP Windows.Devices.Portable