gpt4 book ai didi

c# - 使用 x :Bind 通过 Converter 绑定(bind)到当前 DataContext

转载 作者:行者123 更新时间:2023-11-30 16:05:22 27 4
gpt4 key购买 nike

我有以下转换器:

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到我的转换器。

最佳答案

{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:Bind Name, 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;会先执行。此后,DataContextChangedHandler 方法将在初始化时引发 DataContextChanged 事件时被调用。并且将执行 ProcessBindings 方法以使用绑定(bind)数据更新列表项容器元素。

DataContextChangedHandler 方法中,它调用 this.Update(); 方法,该方法调用 Update_(global::xBindWithConverter.Item obj, int phase) 方法最后。但是当调用DataContextChangedHandler方法时,它的args.NewValue值为null,所以中的obj >Update_(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);
}
}

因为objnull,所以Convert中的valuenull,最后在 value.GetType() 处抛出 NPE。

但是如果我们在 {x:Bind} 中使用另一个 Path,比如 {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);
}
}

判断obj是否为null。因此,不会在此处调用 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;
}
}

关于c# - 使用 x :Bind 通过 Converter 绑定(bind)到当前 DataContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33686149/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com