UWP XAML x:无法识别绑定继承的接口

本文关键字:绑定 继承 接口 识别 XAML UWP | 更新日期: 2023-09-27 18:11:26

在UWP XAML应用程序中使用x:Bind时,请考虑以下事项:

interface IBaseInterface
{
    string A { get; set; }
}
interface ISubInterface : IBaseInterface
{
    string B { get; set; }
}
class ImplementationClass : ISubInterface
{
    public string A { get; set; }
    public string B { get; set; }
}

在Page类中,我们有以下内容:

public partial class MainPage : Page
{
    public ISubInterface TheObject = new ImplementationClass { A = "1", B = "2" };
    //All the rest goes here
}

在MainPage XAML中,我们有以下代码片段:

<TextBlock Text={x:Bind Path=TheObject.A}></TextBlock>

会导致以下编译错误:编译错误WMC1110:无效的绑定路径'A':在类型'ISubInterface'上找不到属性'A'

但是下面的操作是可以的:

<TextBlock Text={x:Bind Path=TheObject.B}></TextBlock>

有没有人知道它是否是UWP XAML平台继承的接口属性不被编译器识别的已知限制?或者这应该被认为是一个bug?有什么已知的变通办法吗?

非常感谢帮助。提前感谢!

UWP XAML x:无法识别绑定继承的接口

是的,经过一些测试和研究,似乎继承的接口属性在使用X:Bind时不能被编译器识别。

作为一种变通方法,我们可以使用传统的Binding来代替X:Bind,如下所示: 在.xaml:
<Grid Name="MyRootGrid">
         <TextBlock Text="{Binding A}"></TextBlock>
</Grid>

在示例:

MyGrid.DataContext = TheObject;

如果你写一个类Foo继承了IFoo。

public class Foo : INotifyPropertyChanged, IF1
{
    public Foo(string name)
    {
        _name = name;
    }
    private string _name;
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    string IF1.Name
    {
        get { return _name; }
        set { _name = value; OnPropertyChanged(); }
    }
}
public interface IF1
{
    string Name { set; get; }
}

当你在页

中写列表时
  public ObservableCollection<Foo> Foo { set; get; } = new ObservableCollection<Foo>()
    {
        new Foo("jlong"){}
    };

如何在xaml中绑定它?

我找到了一个绑定它的方法。您应该使用x:bindPath=(name:interface.xx)在xaml中绑定它。

    <ListView ItemsSource="{x:Bind Foo}">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:Foo">
                <TextBlock Text="x:Bind Path=(local:IFoo.Name)"></TextBlock>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

通过文件顶部的xmlns添加基类的名称空间:

xmlns:base="using:Namespace.Of.Base.Class"