【问题标题】:BindingExpression path error when attempting to bind to a C# class field尝试绑定到 C# 类字段时出现 BindingExpression 路径错误
【发布时间】:2020-04-22 10:37:10
【问题描述】:

我有一个相当简单的绑定(使用{Binding},而不是{x:Bind})但不起作用:

<ListView
    ItemsSource="{x:Bind ViewModel.Items, Mode=OneWay}">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="local:Item">
            <StackPanel>
                <TextBlock Text="{Binding MyField}" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

它编译,但失败并显示错误消息:

错误:BindingExpression 路径错误:在“MyNamespace.Item”上找不到“MyField”属性。 BindingExpression: Path='MyField' DataItem='MyNamespace.Item';目标元素是'Windows.UI.Xaml.Controls.TextBlock'(名称='null');目标属性是“文本”(类型“字符串”)

同样的绑定也适用于x:Bind:

<TextBlock Text="{x:Bind MyField}" />

ViewModel 和项目定义


namespace MyNamespace
{
    public class Item : INotifyPropertyChanged
    {
        public Item()
        {
            // ...
        }

        public readonly string MyField = "Foo";

        // ...
    }

    public class MainPageViewModel : INotifyPropertyChanged
    {
        public MainPageViewModel()
        {
            // ...
        }

        private ItemsCollection _itemsCollection = new ItemsCollection();
        public ObservableCollection<Item> Items
        {
            get { return _itemsCollection.Items; }
        }

        // ...
    }
}

【问题讨论】:

    标签: c# uwp windows-runtime uwp-xaml


    【解决方案1】:

    MyField是C#类字段,不能与{Binding}绑定。

    为避免这种情况,请将MyField 更改为属性:

    public class Item : INotifyPropertyChanged
    {
        // ...
        private readonly string m_myField = "Foo";
        public string MyField { get => m_myField; }
    
    }
    

    那么{Binding MyField}就可以正常工作了。

    this StackOverflow question about the difference between C# fields and properties:

    4. Binding Source 中只能使用属性

    Binding Source 帮助我们减少代码行数。 BindingSource 不接受字段。我们应该为此使用属性。

    这似乎类似于 WPF(也是 can't bind on fields)。

    【讨论】:

      猜你喜欢
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 2022-01-18
      相关资源
      最近更新 更多