【问题标题】:Can't read read-only property even with OneWay mode set即使设置了 OneWay 模式也无法读取只读属性
【发布时间】:2017-03-24 17:20:47
【问题描述】:

视图模型

namespace My.ViewModels
{
    public class ItemViewModel : ObservableObject
    {
        private ItemModel _model;

        public ItemViewModel(ItemModel model)
        {
            _model = model;
        }

        public string Name { get { return _model.Name; } }
    }
}

XAML

<UserControl x:Class="My.Controls.ItemControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:viewModels="clr-namespace:My.ViewModels"
             mc:Ignorable="d"
             d:DesignHeight="421" d:DesignWidth="786"
             d:DataContext="{d:DesignInstance viewModels:ItemViewModel}">
    <Grid Background="White">
        <TextBlock><Run Text="Name:" /> <Run Text="{Binding Name, FallbackValue=Name, Mode=OneWay}" /></TextBlock>
    </Grid>
</UserControl>

错误:

A TwoWay or OneWayToSource binding cannot work on the read-only property 'Name'

我正在尝试对我的 ViewModel 中的只读属性进行 DataBinding。 我已将绑定模式设置为 OneWay.. 但它仍然会引发上述错误。 我没有线索了!任何帮助将不胜感激。

【问题讨论】:

  • 你确定这是你唯一绑定到这个属性的地方吗?如果你完全注释掉 TextBlock 会发生什么?
  • @Taelia,您的属性“名称”没有设置器。这就是为什么在 TwoWay 绑定时会出现该错误的原因。另外,据我所知,TextBlock 无法编辑。
  • @dymanoid 我.. 对你在黑暗中拍摄的能力感到非常惊讶,但有点尴尬,事情就是这么简单。在我的代码中的其他地方,我有一个没有应用 Mode=Oneway 的剩余引用。谢谢!

标签: c# wpf data-binding


【解决方案1】:

要使用 OneWay 绑定,您的属性应该具有 get 和 set。因此,在这种情况下,要解决问题,您只需将 set 添加到您的属性中,如下所示:

public string Name { private set; get { return _model.Name; } 

【讨论】:

  • 我希望底层类保持其只读属性,所以我想使用 OneWay 绑定,而不是 TwoWay 绑定。不过感谢您的努力!
猜你喜欢
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-29
相关资源
最近更新 更多