11

在 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>

这会导致以下编译器错误:XamlCompiler error WMC1110: Invalid binding path 'A' : Property 'A' can't be found on type 'ISubInterface'

但是,以下确实有效:

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

有人知道编译器无法识别继承的接口属性是否是 UWP XAML 平台的已知限制?或者这应该被认为是一个错误?是否有任何已知的解决方法?

非常感谢您的帮助。提前致谢!

4

3 回答 3

9

是的,在进行了一些测试和研究之后,在使用 X:Bind 时,编译器似乎无法识别继承的接口属性。

作为一种解决方法,我们可以使用传统的 Binding 而不是 X:Bind,如下所示:

在 .xaml 中:

<Grid Name="MyRootGrid">
         <TextBlock Text="{Binding A}"></TextBlock>
</Grid>

在 xaml.cs 中:

MyGrid.DataContext = TheObject;
于 2015-09-08T07:16:37.760 回答
1

如果你写了一个类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中绑定它?

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

    <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>
于 2017-12-23T06:49:00.593 回答
0

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

xmlns:base="using:Namespace.Of.Base.Class"
于 2018-06-28T16:23:43.783 回答