3

我有以下转换器:

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>

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

如果我更改以下部分:

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

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

然后它工作。Debug正确输出StickerCategory为值的类型。x:Bind进入转换器的任何原因null以及如何使其工作x:Bind?我正在尝试传递DataContext给我的转换器。

4

3 回答 3

2

{x:Bind}使用生成的代码来实现它的好处,并且在使用不同Path的 in{x:Bind}时,生成的代码有一些差异。

这里我以一个简单的示例为例。如需完整示例,请查看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);
    }
}

当我们{x:Bind Name, Converter={StaticResource ItemConvert}}MainPage.xaml 中使用

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

初始化页面时,element3.DataContextChanged += bindings.DataContextChangedHandler;将首先执行。在此之后,DataContextChangedHandler方法将被调用,因为DataContextChanged在初始化时引发了事件。并且ProcessBindings将执行该方法以使用绑定数据更新列表项容器元素。

DataContextChangedHandler方法中,调用this.Update();方法,Update_(global::xBindWithConverter.Item obj, int phase)最后调用方法。但是当DataContextChangedHandler方法被调用时,它的args.NewValue值是null,所以objinUpdate_(global::xBindWithConverter.Item obj, int phase)方法也是null

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

// 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,最后它抛出一个 NPE 。nullvalueConvertnullvalue.GetType()

但是如果我们Path{x:Bind}like中使用另一个{x:Bind Name, Converter={StaticResource ItemConvert}},生成的代码Update_(global::xBindWithConverter.Item obj, int phase)是不同的:

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

它将确定是否objnull. 所以该XamlBindingSetters.Set_Windows_UI_Xaml_Controls_TextBlock_Text方法不会在这里被调用,NullReferenceException也不会发生。

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

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;
    }
}
于 2015-11-13T10:40:05.897 回答
1

I don't think it is a good idea to use x:bind with converter in general, the goal of using x:bing is to increase performance, while converter will dramatically affect code's performance. you can easily create a readonly field in your model, and when your data is changed, you can raise property changed event, and convert the number there.

For example,

[JsonIgnore]
    public double IsUnreadOpacity
    {
        get { return (IsUnread) ? 1 : 0; }
    }

public bool IsUnread
    {
        get { return _isUnread; }
        set
        {
            if (value == _isUnread)
                return;
            Set(ref _isUnread, value);
            RaisePropertyChanged(nameof(IsUnreadOpacity));
        }
    }
于 2016-03-28T23:15:00.603 回答
0

However, since version 1607 you can use functions with x:Bind and this opens up new opportunities: quick conversion without the added complexity of converters. See the documentation.

于 2020-12-02T15:03:58.050 回答